Is Tail-Recursive Function Invocation Undefined Behavior in C 11?
In C 11, infinite loops without side effects, such as the following, are considered undefined behavior (UB) according to the standard:
<code class="cpp">int main() { while (true) {} }</code>
Does the same logic apply to infinite recursion with no side effects, such as the code below?
<code class="cpp">void foo() { foo(); } int main() { foo(); }</code>
Answer:
Yes, this recursion is also UB, as it does not satisfy the conditions outlined in the C 11 standard for termination criteria.
Specifically, the standard specifies that the implementation may assume that any thread will eventually perform one of the following actions:
Tail-recursive function invocations do not meet any of these criteria and therefore are considered UB.
It's important to note that regardless of this standard interpretation, excessive recursion can still lead to undefined behavior if it exceeds the implementation's limit for nested recursive function calls. This has always been the case in C .
The above is the detailed content of ## Is Tail-Recursive Function Invocation Undefined Behavior in C 11?. For more information, please follow other related articles on the PHP Chinese website!