Home >Backend Development >C++ >## Does Unbounded Recursion in C 11 Qualify as Undefined Behavior?
Is Unbounded Recursion Indefinite Behavior?
In C 11, infinite loops without side effects are considered undefined behavior (UB), as exemplified by the following code:
<code class="cpp">int main() { while (true) {} }</code>
This behavior is dictated by the C standard, which states that an implementation may assume that any thread will eventually terminate, perform I/O operations, access/modify volatile objects, or execute synchronization or atomic operations.
The question arises: does this definition also apply to unbounded recursion, as shown in the following code:
<code class="cpp">void foo() { foo(); } int main() { foo(); }</code>
According to the C standard, the behavior of both programs is undefined because neither of them performs any of the actions specified in the standard's definition of non-UB.
However, it's important to note that even if the C standard did not consider unbounded recursion UB, it could still exhibit undefined behavior if the recursion exceeds the implementation's limit on the number of nested recursive function calls. This has always been the case, and it remains true regardless of the loop's status as UB under the C standard.
The above is the detailed content of ## Does Unbounded Recursion in C 11 Qualify as Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!