octopus
octopus

Reputation: 528

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?

Upvotes: 5

Views: 413

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473627

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.

Upvotes: 15

Related Questions