Infinite loops without side effects are explicitly considered undefined behavior (UB) in the C 11 standard. Consider the following program:
<code class="cpp">int main() { while (true) {} }</code>
This program is UB because it does not perform any meaningful actions and can continue running indefinitely.
Now, let's consider a recursive program:
<code class="cpp">void foo() { foo(); } int main() { foo(); }</code>
Is this program also UB?
The standard states that (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.
This applies to both the infinite loop and the recursion.
Despite this, the recursion can still result in undefined behavior if it exceeds the implementation limit of nested recursive function calls. This has always been the case.
The above is the detailed content of Here are a few title options, keeping in mind the question structure and the article\'s focus: **Option 1 (Direct and focused):** * **Is Recursion in C Undefined Behavior?** **Option 2 (Emphasize. For more information, please follow other related articles on the PHP Chinese website!