Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why ++variable isn't treated as lvalue in C?

Consider the following C code:

#include <stdio.h>

int main(void) {
    int a = 0;
    printf("%d\n", ++a += 1);
}

++ has precedence over += so it should be evaluated first. So we have a on the left and 1 on the right. Now based on my understanding ++a should result in a (only changes its value) which is lvalue so why this statement gives the following error:

lvalue required as left operand of assignment

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The prefix increment operator ++ results in the incremented value of its operand, however it is not an lvalue. Section 6.5.3.1p2 of the C standard: describes the semantics as follows:

The value of the operand of the prefix ++ operator is incremented.
The result is the new value of the operand after incrementation. The
expression ++E is equivalent to (E+=1). See the discussions of
additive operators and compound assignment for information on
constraints, types, side effects, and conversions and the effects of
operations on pointers.

Then section 6.5.16.2p3 regarding compound assignment operators states:

A compound assignment of the form E1 op = E2 is equivalent to the
simple assignment expression E1 = E1 op (E2), except that the lvalue
E1 is evaluated only once, and with respect to an
indeterminately-sequenced function call, the operation of a compound
assignment is a single evaluation.

And 6.5.16p3 regarding the assignment operator further states:

An assignment operator stores a value in the object designated by the
left operand. An assignment expression has the value of the left
operand after the assignment, but is not an lvalue.

So it is explicitly not allowed. Even if it was, an expression such as ++a += 1 would cause a to be modified more than once without an intervening sequence point which would trigger undefined behavior.

This is one of those place where C and C++ differ. C++ does in fact allow the result of the = operator, and by extension compound assingment and prefix ++/--, to be an lvalue.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading