Search code examples
c++loopsrecursionlanguage-lawyerundefined-behavior

Infinite loop vs infinite recursion. Are both undefined?


Infinite loops without side effect are undefined behaviour. See here for the example from cppreference. Much simpler example:

int foo() {
    while(true) {}
    return 42;
}

Now consider the almost equivalent

int bar() {
    if (true) return bar();
    return 42;
}

Does this invoke undefined behaviour as well?

Or phrased differently: What class of error is infinite recursion according to the language?

PS: note that I am aware of the implications at runtime: The loop in principle could run forever, while the recursion will eventually result in a stackoverflow. Though I am mainly interested in what the compiler does to them. Maybe a quite academic question...


Solution

  • No there is no difference. [basic.progress]p1:

    The implementation may assume that any thread will eventually do one of the following:

    • terminate,

    • make a call to a library I/O function,

    • perform an access through a volatile glvalue, or

    • perform a synchronization operation or an atomic operation.

    It doesn't matter how you have your infinite loop; if it doesn't do any of the points above, you get UB. Including the following:

    int bar(int cond) {
        if (cond == 42) bar(cond);
        return 42;
    }
    bar(some_user_input);
    

    The compiler is allowed to assume that some_user_input will never be 42.