Whether in C or C++, I think that this illegal program, whose behavior according to the C or C++ standard is undefined, is interesting:
#include <stdio.h>
int foo() {
int a;
const int b = a;
a = 555;
return b;
}
void bar() {
int x = 123;
int y = 456;
}
int main() {
bar();
const int n1 = foo();
const int n2 = foo();
const int n3 = foo();
printf("%d %d %d\n", n1, n2, n3);
return 0;
}
Output on my machine (after compilation without optimization):
123 555 555
I think that this illegal program is interesting because it illustrates stack mechanics, because the very reason one uses C or C++ (instead of, say, Java) is to program close to the hardware, close to stack mechanics and the like.
However, on StackOverflow, when a questioner's code inadvertently reads from uninitialized storage, the most heavily upvoted answers invariably quote the C or C++ (especially C++) standard to the effect that the behavior is undefined. This is true, of course, as far as the standard goes—the behavior is indeed undefined—but it is curious that alternate answers that try, from a hardware or stack-mechanical perspective, to investigate why a specific undefined behavior (such as the output above) might have occurred, are rare and tend to be ignored.
I even remember one answer that suggested that undefined behavior could include reformatting my hard drive. I didn't worry too much about that, though, before running the program above.
My question is this: Why is it more important to teach readers merely that behavior is undefined in C or C++, than it is to understand the undefined behavior? I mean, if the reader understood the undefined behavior, then would he not be the more likely to avoid it?
My education happens to be in electrical engineering, and I work as a building-construction engineer, and the last time I had a job as a programmer per se was 1994, so I am curious to understand the perspective of users with more conventional, more recent software-development backgrounds.