Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-26 12:19:02
Original
963 people have browsed it

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

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

This provision applies to both the loop example and the following recursive program:

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!