3

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?

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • 4
    missing `return` is undefined behavior. The compiler is not mandated to procude anything meaningful from your code. – 463035818_is_not_an_ai Jul 30 '21 at 12:48
  • 1
    *Is this something one would consider a compiler bug?* No. – Eljay Jul 30 '21 at 12:48
  • 1
    The compiler can assume the function never reaches the end because that would be Undefined Behavior. Thus, it can assume the loop never ends. This is not a compiler bug, it's an error in your code. – François Andrieux Jul 30 '21 at 13:02
  • This is an interesting example of the consequences of UB because it simply and clearly shows that UB can impact behavior without control every actually reaching the point that contains the UB. – François Andrieux Jul 30 '21 at 13:17

2 Answers2

8

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".

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

You can think of undefined behavior as: It is not defined what output the compiler produces when asked to compile your code.

Actually the "undefined" refers to the observable behavior of the program the compiler creates from your code, but it boils down to the same.

This is not a compiler bug.

You asked the compiler to return a bool from a function without returning a bool from the function. There is simply no way the compiler can do that right, and that isn't the compilers fault.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185