c++ - 无限循环与无限递归。两者都未定义吗?

标签 c++ loops recursion language-lawyer undefined-behavior

没有副作用的无限循环是未定义的行为。参见 here来自 cppreference 的示例.更简单的例子:

int foo() {
    while(true) {}
    return 42;
}

现在考虑几乎等同的

int bar() {
    if (true) return bar();
    return 42;
}

这是否也会调用未定义的行为?

或者换种说法:根据语言的不同,无限递归属于哪一类错误?

PS:请注意,我知道运行时的含义:循环原则上可以永远运行,而递归最终将导致计算器溢出。尽管我主要对编译器对它们所做的事情感兴趣。也许是一个相当学术的问题......

最佳答案

不,没有区别。 [basic.progress]p1 :

The implementation may assume that any thread will eventually do one of the following:

  • terminate,

  • make a call to a library I/O function,

  • perform an access through a volatile glvalue, or

  • perform a synchronization operation or an atomic operation.

无限循环的方式并不重要;如果它没有执行上述任何一点,您将获得 UB。包括以下内容:

int bar(int cond) {
    if (cond == 42) bar(cond);
    return 42;
}
bar(some_user_input);

允许编译器假定 some_user_input 永远不会是 42。

关于c++ - 无限循环与无限递归。两者都未定义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55734648/

相关文章:

c++ - 如何使用 CMAKE 在 OSX 包中包含库

c++ - 问题 : 2d Vector (nested Vector) with datatype of new class

java - 需要解释以下java代码的输出

c - 在 Windows 上迭代目录时查找句柄无效

c++ - 如何制作递归函数,它需要检查给定字符串中当前字母及其旁边的字母是小写还是大写?

c++ - 关于类似于 scanf 的函数的问题

c++ - 具有两个 int 列表的 structinit 减少为一个 int

ruby-on-rails - Rails : Why is my . 每个循环都被跳过了吗?

algorithm - 笛卡尔幂 - 通过递归

perl - 如何防止无限递归(使用 Moose)?