Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cant understand this output?

Status
Not open for further replies.

tijoriwalaritesh

Programmer
Jan 12, 2006
1
US
Below is a simple program.

int i = 0;
printf("%d %d %d %d", i++, i==1, i, ++i)

Its giving this output:
On Sun Solaris 8:
0 1 2 2
On Linux:
1 1 1 1
On Windows:
0 1 1 2

Can any one explain me how the compiler behaves in any particular case. I know the code is compiler dependent. Lets assume on linux.

also check your explanation with this one:

int i = 0;
printf("%d %d %d %d", (i++) + (++i), i==1, i, ++i)
 
The Windows output is correct. I don't have a clue what's going on with UNIX though?
 
Indeed you have an incorrect statement:
Code:
printf("%d %d %d %d", i++, i==1, i, ++i)
See
C++ Std said:
Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). ...
Incr/decr ops have side effect so arg list values are undefined in this case. It's an excellent example of a classic trap with evaluation order. You may have different results not only on Unix/Windows but also on different implementation on the same system.
Be careful with side effect operations.
 
Moreover: result of incr/decr op is in effect after full arg list evaluation, so you may have i == 0, 1 or 2 in the moment of i == 1 evaluation.
 
> printf("%d %d %d %d", i++, i==1, i, ++i)
They're all right, and they're all wrong.

Multiple side effects on the SAME variable between sequence points are ALWAYS UNDEFINED within the C language.

Basically, the code is broken.


--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top