This is ternary operator: (statement)?(if true):(if false) right?
but why this code doesn't work properly?
int a=10, b=20;
(a<b)? a++, b++ : a--, b--;
This is ternary operator: (statement)?(if true):(if false) right?
but why this code doesn't work properly?
int a=10, b=20;
(a<b)? a++, b++ : a--, b--;
The comma operator has a lower precidence than the ternary operator. Since the colon can't be orphaned, you get away with the first comma, but not the second one. The compiler is understanding your code as:
((a<b)? a++, b++ : a--), b--;
You need to use parentheses to group at least the second comma expression, and for ease of reading I would do both:
(a<b)? (a++, b++) : (a--, b--);
The conditional operator is defined in C++ like
conditional-expression:
logical-or-expression
logical-or-expression ? expression : assignment-expression
So this expression statement
(a<b)? a++, b++ : a--, b--;
is equivalent to
( (a<b)? a++, b++ : a-- ), b--;
because the assignment expression has a higher priority than the comma expression.
You should write at least like
(a<b)? a++, b++ : (a--, b--);
or for clarity like
( a < b )? ( a++, b++ ) : (a--, b--);
Take into account that there is a difference between the conditional operator in C++ and the conditional operator in C. In C the conditional operator is defined like
conditional-expression:
logical-OR-expression
logical-OR-expression ? expression : conditional-expression
It means for example that this record in C+++
( a < b )? a = b : b = a;
is equivalent to
( ( a < b )? a = b : b = a );
while in C this record is equivalent to
( ( a < b )? a = b : b ) = a;
and the C compiler will issue an error.
On the other hand this record in C++
( ( a < b )? a = b : b ) = a;
is valid.:)