-1

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--;
  • Operator precedence again... Look it up. And define *properly* next time. – LogicStuff Jan 09 '17 at 11:26
  • 1
    Writing a ternary like this only leads to confusion, and isn't really more readable or quicker to write than a simple `else-if`, since there's two assignments involved for each outcome. Basically, you'd need to include parenthesis, though you shouldn't be writing the ternary in the first place(imo). – George Jan 09 '17 at 11:31
  • @George: A ternery operator like this *might* be appropriate as the third expression in a *for-statement*. – Martin Bonner supports Monica Jan 09 '17 at 13:02

2 Answers2

3

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--);
2

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.:)

Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303