p.77 K&R C says the output of the following program is undefined, but current version of Xcode gives no warning. Is it still undefined in current standard? What about in
The result isn't actually undefined, just unspecified.
The difference is that undefined behavior means anything can happen, including behavior that seems to be entirely unrelated to anything in the program at all. The classic line is that it "makes demons fly out of your nose."
Unspecified means that you have no way of knowing which call of my_m
will be evaluated first and which will be evaluated second, but it will be1 one invocation and then the other. One call will start and run to completion then the other call will start and run to completion--the two won't be interleaved or anything like that. The only thing that's unpredictable is the order in which the two calls are made (and yes, under current C and C++ standards, the order is still 100% unpredictable).
In both C# and Java the order of evaluation is specified as left to right.
1. Or at least it'll act as if it did. Both C and C++ follow what's usually called the "as if rule" that allows a compiler to do things differently as long as it does so in a way that maintains the specified externally visible behavior.
A compiler won't warn you about all undefined programs. In the following line:
printf("%d" , my_m() - my_m());
the order of the calls my_m()
is unspecified. The compiler might decide to call either the first one or the second one first. Since the function returns 42
on the first call and 57
on the second call the result is either 42 - 57
or 57 - 42
.
Edit: I missed the difference between undefined and unspecified, see Jerry Coffins answer for details about that.