# ++x returns lvalue but x++ return rvalue

Discussion in 'C++' started by Chris Mantoulidis, Dec 28, 2003.

1. ### Chris MantoulidisGuest

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,

Chris Mantoulidis, Dec 28, 2003

2. ### Severin EckerGuest

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

Severin Ecker, Dec 28, 2003

3. ### Rob WilliscroftGuest

Chris Mantoulidis wrote in
news::

> 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 <insert your favourate UB nonsence here>.

>
> 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.
--
http://www.victim-prime.dsl.pipex.com/

Rob Williscroft, Dec 28, 2003
4. ### Tim ThrelfallGuest

"Chris Mantoulidis" <> wrote in message
news:...
> 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,

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]

Tim Threlfall, Dec 28, 2003
5. ### Chris MantoulidisGuest

Thanks all for the replies. It all seems clear now.

Chris Mantoulidis, Dec 29, 2003