没有副作用的无限循环是未定义的行为。参见 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/