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...
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.
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.
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.
Infinite recursion is a special case of an infinite loop that is caused by recursion.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With