Mail Archives: djgpp/1999/11/01/13:46:05
On Mon, 1 Nov 1999 19:54:22 +0800, "Jason News" <hello AT mymail DOT com>
wrote:
> Hi everyone,
> can anyone tells me why
> int x=5, y=5;
> printf ("1st %d, 2nd %d\n" ++x, y++");
> will show 1st 6, 2nd 5
Yes. That's correct.
> int x=5
> prinf ("1st %d, 2nd %d\n" ++x, x++");
> will show 1st 7, 2nd 5
What this statement will show is completely undefined. It may show
different results with different compilers and different results on
mondays and sundays and it may even not show anything because your
computer may crash.
The order in which arguments of an argument list are evaluated is
unspecified. Thus the compiler may choose to execute 'x++' and '++x'
in any order. This alone would make the output useless.
But the worst problem is that you are modifying x more than once in an
expression with no intervening "sequence points". In this case the
whole thing is just "wrong and illegal".
It's the same as if you would write the nonsense
++x + x++
which is just garbage which casually compiles. The problem with C is
that not every syntactically legal construction will produce a
meaningful result.
A good rule is : Never use the variable name 'x' a second time in an
expression where x++ or ++x occurs. The only legal exceptions are
logical expressions like
a = y<0 ? x : ++x;
or
if ( x || ++x )
where the different instances of 'x' appear at different sides of the
operation ( : || )
Regards
Horst
- Raw text -