++x returns lvalue but x++ return rvalue

C

Chris Mantoulidis

Why is that? Why does ++x return lvalue and x++ return rvalue?

for example, this will work

++x = 10;

it will set x to 10...


but this won't, cuz x++ is rvalue:

x++ = 10; //ERROR

TIA,
cmad
 
S

Severin Ecker

hi!
but this won't, cuz x++ is rvalue:

x++ = 10; //ERROR
thats because the post-increment operator returns a temporary with the value
of x before the increment, not x itself.

on the other side the pre-increment operator increments x and then returns
x.

regards,
sev
 
R

Rob Williscroft

Chris Mantoulidis wrote in
Why is that? Why does ++x return lvalue and x++ return rvalue?

for example, this will work

++x = 10;

Well it might do what you expect, but it introduces undefined
behaviour (aka UB) as it modifies x twice without an intervening
sequence point. So don't do it.

Note if x is a User Defined Type (aka UDT) then since operator ++()
is a function call, there is an intervening sequence point and the
code is ok, but then the result of ++x is what ever operator ++()
returns which isn't nessaseraly an lvalue.
it will set x to 10...

or 11 or any possible value or it may cause a processor exception
or said:
but this won't, cuz x++ is rvalue:

x++ has to be an rvalue as it has a different actual (post sequence
point) value than x (i.e. x - 1).
x++ = 10; //ERROR


void f( int & y )
{
y = 10;
}

int main()
{
int x = 1;
f( ++x );
}

The above is ok as the function call f() intoduces a sequence point,
i.e. x is updated before the call is made.

HTH.

Rob.
 
T

Tim Threlfall

Chris Mantoulidis said:
Why is that? Why does ++x return lvalue and x++ return rvalue?

for example, this will work

++x = 10;

it will set x to 10...


but this won't, cuz x++ is rvalue:

x++ = 10; //ERROR

TIA,
cmad

It should be noted that ++x=10; is undefined for inbuilt types, as stated in
section 5.0.4 of the standard:

Between the previous and next sequence point a scalar object shall have its
stored value modified at most once by the evaluation

of an expression. Furthermore, the prior value shall be accessed only to
determine the value to be stored.

The requirements of this paragraph shall be met for each allowable ordering
of the subexpressions of a full

expression; otherwise the behavior is undefined. [Example:

i = v[i++]; // the behavior is unspecified

i = 7, i++, i++; // i becomes 9

i = ++i + 1; // the behavior is unspecified

i = i + 1; // the value of i is incremented

-end example]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top