Consider the following program, which is obviously buggy:
#include <cstdio>
double test(int n) {
if (n % 2 == 0)
return 0.0;
// warning: control reaches end of non-void function
}
int main() {
printf("%.9lf\n", test(0));
printf("%.9lf\n", test(1));
printf("%.9lf\n", test(2));
printf("%.9lf\n", test(3));
return 0;
}
When compiled with g++, version 4.2.4 (Ubuntu 4.2.4-1ubuntu4) on a 32-bit Ubuntu 8.04, it produces the following output:
0.000000000
nan
0.000000000
nan
When compiled with g++, version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) on a 64-bit Ubuntu 10.04, it produces the following output:
0.000000000
0.000000000
0.000000000
0.000000000
It seems that the older compiler does some extra work in order to return NaN instead of garbage, while the newer compiler simply returns whatever there is in memory. What exactly causes this difference in behavior and how to control it and make it predictable across different compiler versions?
EDIT: Sorry for not mentioning undefined behavior earlier. I know that the difference comes from the fact that this program has undefined behavior. What I’d like to know why the former gcc version seems to put some effort and produce code that consistently returns NaN and when this behavior changed to the one observed in the latter gcc version. Also, by “predictable” I meant not how to write good programs in C++, but how to control this gcc behavior (maybe with some command line options?).
The code you show has undefined behavior, by failing to return a value in
testfrom all control paths.There is nothing to expect, and nothing you can do to control it, except by writing a correct program in the first place.
EDIT: I maintain that you shouldn’t rely on what the compiler seems to do.
Even if you think you should, you shouldn’t.
Looking at the dissasembly will reveal what this particular piece of code will be compiled into, but you will not be able to generalize to anything else than this particular piece of code, especially in the presence of optimizations. Undefined behavior really means what you think it does: unless you happen to master GCC’s codebase, there will be no guarantee that what you observe will be reproducible in another context.
The only sensible solution here is to compile with -Wall and fix those “not all return paths return a value”, so that the behaviour is 1) defined, 2) defined by you.