Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precedence of the C++ Comma Operator

Hi I am a little confused with the following code:

int main()
{
    int sum = 0, val = 1;
    while(val <= 10)
        sum += val, ++val;     //source of problem

    cout<<"Sum of 1 to 10 inclusive is " << sum << endl;
    //
    return 0;
}

I am currently learning about operator precedence. Know that the comma operator has the lowest precedence among the C++ operators, I was hoping that the statement in the while loop evaluate in the following order:

++val; //so that val is incremented to 2 the first time the code in the while loop is evaluated
sum += val; //so that the incremented value of val is added to the sum variable 

But the code evaluated in this order instead:

sum += val;
++val;

Why did the comma operator seem to have affected the order of evaluation?

like image 582
octopus Avatar asked Dec 11 '19 16:12

octopus


People also ask

What is the priority of C logical operators?

Precedence. Among logical operators, the NOT ( ! ) operator has the highest precedence and it associates from right to left. The precedence of AND ( && ) operator is higher than OR ( || ) operator and they both associates from left to right (see the full precedence table).

How does a comma operator work?

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.

What is comma and sizeof operator in C?

The comma operator has no special meaning to sizeof . sizeof(b, a) examines the complete expression (b, a) , works out the resultant type, and computes the size of that type without actually evaluating (b , a) .


1 Answers

This is not about precedence; it's about order of evaluation. The comma operator, unlike most other C++ operators (pre-C++17), strictly enforces a specific order of evaluation. Comma expressions are always evaluated left-to-right.

like image 84
Nicol Bolas Avatar answered Nov 11 '22 19:11

Nicol Bolas