Why is the following illegal in C?
y = (w + x)++;
According to my book, this is illegal, but I don't see why.
In C/C++, Increment operators are used to increase the value of a variable by 1. This operator is represented by the ++ symbol. The increment operator can either increase the value of the variable by 1 before assigning it to the variable or can increase the value of the variable by 1 after assigning the variable.
In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.
1) Increment Operators: The increment operator is used to increment the value of a variable in an expression. In the Pre-Increment, the value is first incremented and then used inside the expression. Whereas in the Post-Increment, the value is first used inside the expression and then incremented.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With