Why is the following illegal in C?
y = (w + x)++;
According to my book, this is illegal, but I don't see why.
Why is the following illegal in C?
y = (w + x)++;
According to my book, this is illegal, but I don't see why.
In i++
, the value of i
is changed. After execution, i
's value is one plus its previous value. You can't store a value in w+x
, though, and so you can't do any of the following, which all (if they worked) would have more or less the same effect:
w+x = w+x+1;
w+x += 1;
(w+x)++;
Something that can be placed on the left hand side of an assignment is typically called an lvalue (l is for left). The concise way of saying this is that ++
can only be applied to lvalues, and w+x
isn't an lvalue. You can read more about lvalues (and other kinds of values) in this question and its answers:
According to Dennis M. Ritchie's book: "The C Programming Language":
2.8 Increment and Decrement Operators
(page 44)
The increment and decrement operators can only be applied to variables; an expression like
(i + j)++
is illegal. The operand must be amodifiable lvalue
of arithmetic or pointer type.
Because an expression
i++;
is equivalent to:
i = i + 1;
So an expression like:
(i + j)++;
something like equivalent to:
(i + j) = (i + j) + 1; // meaning less
That looks meaning less, we can't modify expression.
Related: An interesting bug one may like to know about in gcc 4.4.5 is that expression j = ++(i | i);
compiles that should produce l-value error. Read: j = ++(i | i);
and j = ++(i & i);
should an error: lvalue?
Read about modifiable lvalue from (1) Expression must be a modifiable lvalue error and (2) msdn docs: Lvalues and Rvalues
y = x++
returns the value of the increment on the variable x
.
y = (x + z)++
fails because (x + z)
is NOT a variable.
It's illegal because (w+x)
is not a legal left hand side value.
A left hand side value is a value that can be assigned to (I.E. a variable).
It is illegal because (x+y)
is not a variable.
Consider
a++
is a = a + 1
(x+y)++
is what? (x+y) = (x+y) + 1
?
Post inctrement and decrement requires l-value
(say a variable which comes on left side). w+x
is not a variable. Incrementing w+x
is like incrementig 3 + 4
, which is illegal.