2

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;
Naveen
  • 7,944
  • 12
  • 78
  • 165

2 Answers2

6

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);
ouah
  • 142,963
  • 15
  • 272
  • 331
  • 8
    Also: `foo = i < 10 ? 10 : 12;` – Nemanja Boric Sep 15 '13 at 10:51
  • 2
    @NemanjaBoric - And it is also more readable – Ed Heal Sep 15 '13 at 10:53
  • @EdHeal more readable for me would be to use a `if` statement here. – ouah Sep 15 '13 at 10:54
  • 1
    I'm a bit confused about what the Standard says here (maybe because I'm coming from C++): C99 6.5.15 says a *conditional-expression* is either a *logical-OR-expression* or a *logical-OR-expression* `?` *expression* `:` *conditional-expression*. So, while the first one can be an *assignment-expression*, I don't think the second one can be. C++ OTOH has a different (grammatical) definition, where the expression after the colon is an *assignment-expression*. – dyp Sep 15 '13 at 10:58
  • 1
    Oh, nevermind. `(` *expression* `)` is a *primary-expression* and therefore a *logical-OR-expression*. (This probably means that `i<10 ? foo=10 : (foo=12);` is legal, too.) – dyp Sep 15 '13 at 11:02
3

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

NPE
  • 486,780
  • 108
  • 951
  • 1,012