nikel
nikel

Reputation: 3564

Unexpected error with conditional operator

The code below compiles well

int a=5,b=4,c;
a>b?30:40;

Also does,

int a=5,b=4,c;
a>b?c=30:40;

But why this does not work?

int a=5,b=4,c;
a>b?c=30:c=40;

Upvotes: 1

Views: 164

Answers (3)

Joey Adams
Joey Adams

Reputation: 43380

You are being bitten by precedence. ?: has very low precedence, but not as low as = or , (see the operator precedence table).

Your code is parsed as:

(a>b ? c=30 : c) = 40;

Rather than:

a>b ? c=30 : (c=40);

You don't need parenthesis around c=30 because ? and : act like parentheses to the expression within.


Believe it or not, (a>b ? c=30 : c) = 40 is valid C++ (but not valid C). The expression (a>b ? c=30 : c) is an lvalue referencing the variable c, to which 40 is assigned.

Upvotes: 7

Dmitri
Dmitri

Reputation: 9375

The last one:

int a=5,b=4,c;
a>b?c=30:c=40;

fails because it's trying to assign 40 to a>b?c=30:c, which obviously won't work. The = has lower precedence, and a>b?c=30:c is a valid expression (though you can't assign to it). The = in the c=30 part is sort of an exception because it's in the middle of the ternary operator, between the ? and the :. To fix it you'd simply need to add parentheses around the c=40 so that it's evaluated as a single value for the 'else' part of the ternary operator, i.e. a>b?c=30:(c=40);

The second example

a>b?c=30:40;

doesn't assign anything to c unless a is greater than b... which it is when a is 5 and b is 4, as in this case; but note that if a were not greater than b, no assignment would occur.

From the first example

a>b?30:40

is a valid expression, with a value of 30 or 40, but you're not doing anything with that value so of course it serves no purpose there.

Of course, you'd normally use something more like:

c = a>b ? 30 : 40;

where a>b ? 30 : 40 will evaluate to 30 or 40, which is then assigned to c. But I suspect you know that and simply want to know why the c=40 is not treated as a single value for the 'else' part of the ternary operator in the last example.

Upvotes: 0

user7116
user7116

Reputation: 64078

You've run into a precedence problem with the = operator. If you insist on assignment inside of your ternary operator, merely wrap the sub expressions in parentheticals:

int d = a > b ? (c = 30) : (c = 40); // explicit precedence

Upvotes: 1

Related Questions