Home > Backend Development > C++ > body text

## Is Infinite Recursion in C Considered Undefined Behavior?

Susan Sarandon
Release: 2024-10-26 18:47:03
Original
534 people have browsed it

##  Is Infinite Recursion in C   Considered Undefined Behavior?

Is Infinite Recursion Undefined Behavior (UB)?

In the realm of C programming, the question of whether infinite recursion constitutes Undefined Behavior (UB) has been a topic of debate. While certain scenarios involving loops have been identified as UB, it remains uncertain whether infinite recursion itself falls under this classification.

In C 11, a program containing an infinite loop with no side effects, as shown below, is considered UB:

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

This is documented in the C standard as 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." Since an infinite loop without side effects will never perform any of these actions, it's considered UB.

The question then arises whether the following program, involving infinite recursion, also constitutes UB:

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

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

While the above program could be intuitively assumed to be UB, the standard does not explicitly address this specific scenario. The relevant passage in 1.10p24 refers to loops, not recursion.

However, it's worth noting that excessive recursion can lead to the implementation limit of the number of nested recursive function calls being exceeded. This has always been the case and can result in undefined behavior, regardless of the UB classification of recursion itself.

The above is the detailed content of ## Is Infinite Recursion in C Considered Undefined Behavior?. 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!