unexpected result

J

Jim Hester

The following stemmed from a slightly bizarre line in a student's work that
surprised my by doing what HE wanted it to do. Question: Are the second and
third cases below correct by some interpretation of the language semantics
that I'm missing, or is it some kind of register-optimization bug (or
something else)?

int i = 1;

int j;

j = i++; // i ends up 2, j ends up 1 (as expected)

cout << "i=1; j = i++; i == " << i << " j == " << j << endl << endl;



int k = 1;

k = k++; // k ends up 2 - not exptectd.

cout << "K=1; k = k++; k == " << k << endl << endl;



int m = 1;

int p;

m = ( p = m++ ); // p ends up 1 as expected, but m remains 2 (not set back
to 1)

cout << "m=1; m = (p = m++); p == " << p << " m == " << m << endl << endl;
 
V

Victor Bazarov

Jim said:
The following stemmed from a slightly bizarre line in a student's work that
surprised my by doing what HE wanted it to do. Question: Are the second and
third cases below correct by some interpretation of the language semantics
that I'm missing, or is it some kind of register-optimization bug (or
something else)?

[... i=i++ again ...]

Search in the news archives for "undefined behaviour".

V
 
R

red floyd

Jim said:
k = k++; // k ends up 2 - not exptectd.

m = ( p = m++ ); // p ends up 1 as expected, but m remains 2 (not set back
to 1)

Both of these invoke undefined behavior. It is free to work "as
expected", or do anything else, including blow up your monitor, reformat
your hard drive, or even contact the Pentagon and start WWIII.
 
B

Ben Pope

Jim said:
The following stemmed from a slightly bizarre line in a student's work that
surprised my by doing what HE wanted it to do. Question: Are the second and
third cases below correct by some interpretation of the language semantics
that I'm missing, or is it some kind of register-optimization bug (or
something else)?

int i = 1;

int j;

j = i++; // i ends up 2, j ends up 1 (as expected)

cout << "i=1; j = i++; i == " << i << " j == " << j << endl << endl;



int k = 1;

k = k++; // k ends up 2 - not exptectd.

This is undefined behaviour. Search for "sequence point".

Ben Pope
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top