Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operators in C [duplicate]

Tags:

c

If the following code works

i=1;
i<10 ? printf("Hello") : printf("Bye");

then the assignment should also work.What is the reason which makes it to produce error?

i<10 ? foo=10 : foo=12;
like image 672
Naveen Avatar asked Aug 30 '26 16:08

Naveen


2 Answers

What is the reason which makes it to produce error?

Operator precedence.

i<10 ? foo=10 : foo=12; is equivalent to (i<10 ? foo=10 : foo) = 12;

Use parentheses to fix your issue:

i<10 ? (foo=10) : (foo=12);
like image 194
ouah Avatar answered Sep 01 '26 06:09

ouah


The reason is operator precedence. The following will work:

i<10 ? (foo=10) : (foo=12);

Your original expression gets parsed as

(i<10 ? foo=10 : foo)=12;

giving rise to the error (lvalue required as left operand of assignment).

like image 31
NPE Avatar answered Sep 01 '26 07:09

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!