Mailinglist Archive: opensuse-programming (32 mails)

< Previous Next >
Re: [suse-programming-e] post increment and self assignment problem
  • From: John Lamb <J.D.Lamb@xxxxxxxxxxxxxx>
  • Date: Sat, 06 Jul 2002 09:05:39 +0000
  • Message-id: <3D26B2E3.4060702@xxxxxxxxxxxxxx>
Verdi March wrote:
int x = 10;
x = x++;
cout << "x = " << x << '\n';

The execution results in:
x = 11

As I recall, the increment is done after the expression is evaluated in full - I can't actually think of any other sensible place to do it. So the compiled code should do something like

move x to x # x = 10 and probably optimised out
increment x # x = 11

This makes more sense if you think how you might generate assembly code from an expression.

In a similar way

int x = 10;
x = y = x++;
cout << "x = " << x << '\n';
cout << "y = " << x << '\n';

will give
x = 11
y = 10

I would avoid this kind of code in a real program because it's inefficient, difficult to read, and there may be a danger that some compiler will get it wrong. On the other hand, it's a good way to find out how C++ works.

JDL

--

Non enim propter gloriam, diuicias aut honores pugnamus set propter
libertatem solummodo quam Nemo bonus nisi simul cum vita amittit.


< Previous Next >
List Navigation
References