Home > Backend Development > C++ > ## Is Tail-Recursive Function Invocation Undefined Behavior in C 11?

## Is Tail-Recursive Function Invocation Undefined Behavior in C 11?

Barbara Streisand
Release: 2024-10-25 11:17:02
Original
430 people have browsed it

## Is Tail-Recursive Function Invocation Undefined Behavior in C  11?

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>
Copy after login

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>
Copy after login

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:

  • Terminate
  • Call a library I/O function
  • Access or modify a volatile object
  • Perform a synchronization or atomic operation

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template