Take the following minimum example:
#include <stdio.h>
bool test(){
for (int i = 0; i < 1024; i++)
{
printf("i=%d\n", i);
}
}
int main(){
test();
return 0;
}
where the return statement in the test function is missing. If I run the example like so:
g++ main.cpp -o main && ./main
Then the loop aborts after 1024 iterations. However, if I run the example with optimizations turned on:
g++ -O3 main.cpp -o main && ./main
Then this is optimized and I get an endless loop.
This behavior is consistent across g++ version 10.3.1 and clang++ version 10.0.1. The endless loop does not occur if I add a return statement or change the return type of the function to void.
I am curious: Is this something one would consider a compiler bug? Or is this acceptable, since a missing return statement is undefined behavior and thus we lose all guarantees about what happens in this function?
Your function is declared as
bool test(), but your definition never returns anything. That means you've broken the contract with the language and have be put in a time out in undefined behavior land. There, all results are "correct".