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?
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).
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.
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) .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With