Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the increment operator in C

Tags:

c

syntax

lvalue

Why is the following illegal in C?

y = (w + x)++;

According to my book, this is illegal, but I don't see why.

like image 352
Dstubred Lopez Avatar asked Oct 09 '13 14:10

Dstubred Lopez


People also ask

How does increment operator work in C?

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.

What is ++ i and i ++ in C?

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.

What does the increment operator do?

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.


2 Answers

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:

  • What are rvalues, lvalues, xvalues, glvalues, and prvalues?
like image 74
Joshua Taylor Avatar answered Oct 19 '22 04:10

Joshua Taylor


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 a modifiable 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

like image 30
Grijesh Chauhan Avatar answered Oct 19 '22 05:10

Grijesh Chauhan