Home >Backend Development >C++ >## Does Unbounded Recursion in C 11 Qualify as Undefined Behavior?

## Does Unbounded Recursion in C 11 Qualify as Undefined Behavior?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 00:59:02706browse

## Does Unbounded Recursion in C  11 Qualify as Undefined Behavior?

Is Unbounded Recursion Indefinite Behavior?

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

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

This behavior is dictated by the C standard, which states that an implementation may assume that any thread will eventually terminate, perform I/O operations, access/modify volatile objects, or execute synchronization or atomic operations.

The question arises: does this definition also apply to unbounded recursion, as shown in the following code:

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

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

According to the C standard, the behavior of both programs is undefined because neither of them performs any of the actions specified in the standard's definition of non-UB.

However, it's important to note that even if the C standard did not consider unbounded recursion UB, it could still exhibit undefined behavior if the recursion exceeds the implementation's limit on the number of nested recursive function calls. This has always been the case, and it remains true regardless of the loop's status as UB under the C standard.

The above is the detailed content of ## Does Unbounded Recursion in C 11 Qualify as Undefined Behavior?. 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