简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM