-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Does printf output depends on compilers or operating systems? I have
one program
int main()
{
int i=5;
printf("%d %d %d",i++,i++,i++);
return 0;
}
Output of this program on DOS (TC) 7 6 5
Output of this program on Windows (VC++) 5 5 5
Output of this program on Linux (GCC) 7 6 5
so these outputs conlude that behaviour of this program is undefined.
is that right?
Right. And the output can be /anything/ (although, numbers are
reasonable for undefined behaviour)
but can anybody have any other answer to this behaviour in terms of OS
or Compiler???
The values can be explained by compiler behaviour outside the scope of
the C standard.
Consider this: the C standard makes no specification of the order in
which function arguments are evaluated, and leaves the order to the
compiler implementor. Typical orders are right-to-left, and
left-to-right, but other orders are possible.
Right-to-left order would take an argument list of fn(a,b,c), and
evaluate the c argument before the b argument, and
evaluate the b argument before the a argument
Left-to-right order would take an argument list of fn(a,b,c) and
evaluate the a argument before the b argument, and
evaluate the b argument before the c argument
Also, the C standard makes no guarantees of /when/ changes will be made,
other than that changes will be guaranteed to be made at "sequence
points" in the code. The compiler is free to make some changes prior to
the sequence point; the programmer is restricted to assuming that such
changes haven't actually happened until the sequence point.
Taken together, these two points (order evaluation and execution) can
explain your results. Keep in mind, this is guesswork, and is completely
outside the realm of the C standard.
So, let's guess...
For your TC and GCC results
Output of this program on DOS (TC) 7 6 5
Output of this program on Linux (GCC) 7 6 5
it appears that
a) each compiler evaluates function arguments right to left, and
b) each compiler makes changes at the comma that separates function
arguments
which makes the leftmost argument 5 (post incremented to 6),
the middle argument 6 (post incremented to 7), and
the rightmost argument 7 (post incremented to 8)
OTOH, for your VC++ results,
Output of this program on Windows (VC++) 5 5 5
it appears that the compiler makes changes after all the arguments have
been parsed, and there is no hint at the order of evaluation of the
arguments.
And, that is why dependance on undefined behaviour is not a good idea.
- --
Lew Pitcher, IT Specialist, Enterprise Data Systems
Enterprise Technology Solutions, TD Bank Financial Group
(Opinions expressed here are my own, not my employer's)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)
iD8DBQFDPU9TagVFX4UWr64RAjTrAKDs0QpHcH5dlrHsu43M0wxo+DSP1gCfXx9d
tTPMaN0noTDWtHDy7a+303M=
=oByo
-----END PGP SIGNATURE-----