Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: for-loop is optimized into endless loop if function return statement is missing - compiler bug?

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?

like image 805
networkstudent Avatar asked Nov 05 '25 16:11

networkstudent


2 Answers

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

like image 50
NathanOliver Avatar answered Nov 07 '25 09:11

NathanOliver


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.

like image 32
463035818_is_not_a_number Avatar answered Nov 07 '25 09:11

463035818_is_not_a_number



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!