Home  >  Article  >  Backend Development  >  ## Is Recursion Without Side Effects Undefined Behavior in C ?

## Is Recursion Without Side Effects Undefined Behavior in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 12:19:021000browse

## Is Recursion Without Side Effects Undefined Behavior in C  ?

Is Recursion Without Side Effects Undefined Behavior?

In C 11, infinite loops without side effects, such as the following, are considered undefined behavior (UB):

<code class="cpp">int main() {
   while (true) {}
}</code>

The behavior is UB due to a provision in the ISO C 11 standard (1.10p24) that states:

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 provision applies to both the loop example and the following recursive program:

<code class="cpp">void foo() {
   foo();
}

int main() {
   foo();
}</code>

In this recursive program, there are no side effects, but it is also considered UB because it violates the assumption that any thread will eventually perform one of the actions listed in 1.10p24.

Note that even if this provision did not exist, the recursion could still exhibit undefined behavior if it exceeds the implementation-defined limit for nested recursive function calls. This has always been the case in C , regardless of the version.

The above is the detailed content of ## Is Recursion Without Side Effects Undefined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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