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 C++? Bonus points for similar program in Java and C#.
#include <stdio.h>
int my_m()
{
static int n = 0;
static int m[] = { 42, 57 };
return n++ % 2 == 0 ? m[0] : m[1];
}
int main()
{
printf("%d" , my_m() - my_m());
return 0;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With