Home > Article > Backend Development > ## Is Infinite Recursion in C Considered Undefined Behavior?
Is Infinite Recursion Undefined Behavior (UB)?
In the realm of C programming, the question of whether infinite recursion constitutes Undefined Behavior (UB) has been a topic of debate. While certain scenarios involving loops have been identified as UB, it remains uncertain whether infinite recursion itself falls under this classification.
In C 11, a program containing an infinite loop with no side effects, as shown below, is considered UB:
<code class="cpp">int main() { while (true) {} }</code>
This is documented in the C standard as 1.10p24: "The implementation may assume that any thread will eventually do one of the following: terminate, make a call to a library I/O function, access or modify a volatile object, or perform a synchronization operation or an atomic operation." Since an infinite loop without side effects will never perform any of these actions, it's considered UB.
The question then arises whether the following program, involving infinite recursion, also constitutes UB:
<code class="cpp">void foo() { foo(); } int main() { foo(); }</code>
While the above program could be intuitively assumed to be UB, the standard does not explicitly address this specific scenario. The relevant passage in 1.10p24 refers to loops, not recursion.
However, it's worth noting that excessive recursion can lead to the implementation limit of the number of nested recursive function calls being exceeded. This has always been the case and can result in undefined behavior, regardless of the UB classification of recursion itself.
The above is the detailed content of ## Is Infinite Recursion in C Considered Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!