Does this code contain UB?

int i = 6; i = 7, ++i, i++; 

    3 answers 3

    Operators such as the comma operator, the logical AND operator (&&) and the logical OR operator (||) before calculating the next operand perform all the side effects associated with the expression for the first operand.

    For example, you can write

     std::cout << ( i++, i++, i++ ) << std::endl; 

    or

     if ( i++ > 0 && i++ < 10 ) { /* ... */ } 

    or

     if ( i++ == 0 || i++ % 3 == 0 ) { /* ... */ } 

    The same applies to initialization lists in C ++ . For example,

     int a[] = { i++, ++i }; 

    Or in the class constructor

     struct A { int x; int y; A( int i ) : x( i++ ), y( ++i ) { //,,, } }; 

    If the behavior of the listed operators with respect to side effects is the same in both C ++ and C, then there is an important difference regarding the initialization lists between these two languages. In C, the order of calculating the side effects of initializers in the initialization list is not defined.

    From standard C (6.7.9 Initialization)

    This is an unspecified .152 23 evaluations of the initialization list.

    Compare this quote with a quote from the C ++ standard (8.5.4 List-initialization)

    4 Within the initializer-list-of-braced-init-list, the initializer-clauses are evaluated. This is where each of the initializer compiled with the initializer-clause is associated with the initializer-list. [Note: This evaluation evaluation of holdingsregardlessofthesemanticsoftheinitialization; forexample, itapplies when it comes to the constructor call, even though there are no sequencing constraints. —End note]

      No, there is no UB here, if we consider that the grouping of operators and operands in this expression has the following form

       (i = 7), (++i), (i++); 

      The comma operator orders (sequences) both the computation of the values ​​of its operands and the execution of their side effects. (To put it in the old terminology, the comma operator is the sequence point ).

      First, the left operand will be calculated, and then the right operand. And all the side effects of calculating the left operand will take place even before the calculation of the right operand begins.

      5.19 Comma operator [expr.comma]

      1 [...] A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression. It is sequenced to the left and right side. [...]

        Why did it happen?

        The operation uniquely determines the order (from left to right) of the evaluation of expressions, the result will be the value of the last expression.

        You i will be equal to 9.