Understanding the increment operator in C

Why in C?

y = (w + x)++; 

According to my book, this is illegal, but I do not understand why.

+7
c syntax lvalue
source share
7 answers

In i++ , the value of i changes. After execution, the value of i is equal to one plus its previous value. However, you cannot save the value in w+x , and therefore you cannot perform one of the following actions, which all (if they work) will 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 side of a job is usually called an lvalue (l for the left). In short, this means that ++ can only be applied to lvalues, and w+x not an lvalue. You can learn more about lvalues ​​(and other meanings) in this question and its answers:

  • What are rvalues, lvalues, xvalues, glvalues ​​and prvalues?
+21
source share

According to Dennis M. Ritchie's book, "C Programming Language" :

2.8 Operators increment and decrement

(p. 44)

The increment and decrement operators can only be applied to variables; an expression like (i + j)++ is illegal. The operand must be a modifiable lvalue arithmetic or pointer type.

Because the expression

 i++; 

equivalent to:

 i = i + 1; 

So, an expression like:

 (i + j)++; 

something like equivalent:

 (i + j) = (i + j) + 1; // meaning less 

It looks smaller; we cannot change the expression.

Related: An interesting error that can be described in gcc 4.4.5 is the compilation of the expression j = ++(i | i); , which should lead to an l-value error. Read: j = ++(i | i); and j = ++(i & i); there should be an error: lvalue?

Read about mutable lvalue from (1) The expression must be a mutable lvalue error and (2) msdn docs: Lvalues ​​and Rvalues

+8
source share

y = x++ returns the value of the increment of the variable x .

y = (x + z)++ fails because (x + z) NOT a variable.

+5
source share

This is illegal because (w+x) not the legal value of the left side.

A left-hand side value is a value that can be assigned to a variable (IE a variable).

+4
source share

Post-increment requires l-value , in which w+x not.

+3
source share

This is illegal because (x+y) not a variable.

Consider

a++ a = a + 1

(x+y)++ what? (x+y) = (x+y) + 1 ?

+2
source share

The inctrement and decment column requires l-value (say, the variable that goes to the left). w+x not a variable. The w+x increment is similar to incrementig 3 + 4 , which is illegal.

+2
source share

All Articles