Is it standard C++ code?

L

ljh131

i found something wrong code.

int i = 0;
i = i++;

is it standard c++? peoples say i == 1 in most compilers but anothers
not the same. if so, may be it's not standard code, however i want know
positively.
 
R

Ron Natalie

ljh131 said:
i found something wrong code.

int i = 0;
i = i++;

is it standard c++? peoples say i == 1 in most compilers but anothers
not the same. if so, may be it's not standard code, however i want know
positively.
It's undefined behavior. You are attempting to change a variable
twice between sequence points (once for the assignment and once
for the side-effect of ++).
 
V

Victor Bazarov

ljh131 said:
i found something wrong code.

int i = 0;
i = i++;

is it standard c++?

Yes, in the sense that it will compile. However, the behaviour of
that code is undefined, according to the Standard. So, the usual
advice is: don't do that.
peoples say i == 1 in most compilers but anothers
not the same. if so, may be it's not standard code, however i want know
positively.

If the behaviour is undefined, there is nothing we can say about the
outcome of executing that code from the Standard C++ point of view.

V
 
H

Heinz Ozwirk

ljh131 said:
i found something wrong code.

int i = 0;
i = i++;

is it standard c++? peoples say i == 1 in most compilers but anothers
not the same. if so, may be it's not standard code, however i want know
positively.

Yes, it is standard C++, but the behaviour is not defined by the standard.
In the statement 'i = i++', there is no sequence point and i is modified
more than once. Many compilers might create code such that finaly i == 1,
but it is easy to imagine a sequence of code, that results in i == 0:

1. Evaluate the expression i
2. Increment i
3. Assign the result of step 1 to i

So remember what they tell the kids in TV -- "Don't do that at work"

HTH
Heinz
 
G

Greg Comeau

Yes, it is standard C++, but the behaviour is not defined by the standard.
In the statement 'i = i++', there is no sequence point and i is modified
more than once. Many compilers might create code such that finaly i == 1,
but it is easy to imagine a sequence of code, that results in i == 0:

1. Evaluate the expression i
2. Increment i
3. Assign the result of step 1 to i

So remember what they tell the kids in TV -- "Don't do that at work"

Right, the problem is whether the ++ side-effect takes place
before or after the assignment. But we don't get only those
two choices (which is bad enough) and hence as you say it is
undefined behavior.
 

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,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top