Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 345
463035818_is_not_a_number Avatar asked Apr 17 '19 19:04

463035818_is_not_a_number


People also ask

Are infinite loops undefined behavior?

No thread of execution can execute forever without performing any of these observable behaviors. Note that it means that a program with endless recursion or endless loop (whether implemented as a for-statement or by looping goto or otherwise) has undefined behavior.

What is difference between infinite loop and infinite recursion?

Iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false; infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on the base case.

What is the difference between an infinite loop and recursion in C?

A recursive function keeps calling itself whereas an infinite loop keeps repeating the same block of code. When a function is called, some storage must be reserved to store its return value on the function call stack.

Can recursion causes infinite loop?

Infinite recursion is a special case of an infinite loop that is caused by recursion.


Video Answer


1 Answers

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.

like image 153
Rakete1111 Avatar answered Oct 05 '22 13:10

Rakete1111