What's happening here?
#include <iostream>
using namespace std;
int main(){
int x=0,y=0;
true? ++x, ++y : --x, --y;
cout << "x: " << x << endl;
cout << "y: " << y << endl; //why does y=0 here?
x=0,y=0;
false ? ++x, ++y : --x, --y;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
}
x: 1
y: 0
x: -1
y: -1
The second case seems fine. I would expect both x and y to increment to 1 in the first case but only the left hand operand increments.
The conditional operator of the C programming language works as follows: The condition is evaluated first and the result of the condition is implicitly converted to bool. If the condition evaluates to be true the first statement -- the statement after the question mark will get executed.
The comma operator has the lowest precedence.
The comma operator (,) allows you to evaluate multiple expressions wherever a single expression is allowed. The comma operator evaluates the left operand, then the right operand, and then returns the result of the right operand.
The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.
The first one is equivalent to:
(true ? (++x, ++y) : (--x)), --y;
The second one is equivalent to:
(false ? (++x, ++y) : (--x)), --y;
Thus the --y
is always executed. In the first line, the increments are executed first so x = 1, y = 0
is expected. In the second line, the decrement of x
is executed first so x = -1, y = -1
is expected.
As noted in a comment (to another answer) by Barmar:
And in case anyone is wondering why the comma between
++x
and++y
doesn't have the same effect, it's because(true? ++x)
would not be valid at all. So the compiler keeps scanning until it finds the:
, but beyond that it stops when it reaches a lower precedence operator [(,
in this example) or the end of statement].
The y
is zero because comma has the lowest precedence among all C++ operators. Because its precedence is lower than that of the ternary conditional operator, the conditional operators are parsed as true? ++x, ++y : --x
and false? ++x, ++y : --x
. In both cases, the --y
statement is executed unconditionally.
EDIT The first comma is different because the compiler has found a ?
, so now it needs a :
to complete the "when true" expression of the conditional. That is why both ++x
and ++y
are taken in.
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