我刚刚遇到了以下代码的一个极其奇怪的结果。
#include <iostream>
using namespace std;
const int N = 3;
bool gen(int l1, int l2, int p) {
if(p == N-1) {
if (l1 == l2) {
cout << "sth";
return false;
}
}
else
return gen(l1+1, l2, p+1) || gen(l1, l2+1, p+1));
}
int main() {
if(gen(0,0,0)) cout << "yes";
else cout << "no";
return 0;
}
该程序绝对不执行任何操作,它只是一个模拟。为什么它每次都写是,即使我不允许它在任何地方这样做。此外,输出不包含“某事”这个词。此外,当我更改时:
cout << "sth";
return true;
进入:
cout << "sth";
return false;
它仍然产生 "yes"
作为输出。
怎么会这样?
最佳答案
问题在于,如果 p == N-1
和 l1 != l2
,您的函数将退出而实际上并未触发 return
。如果将其设置为合理的警告级别,您的编译器会就此警告您。
这会触发未定义的行为,因此可能会发生任何输出。 (例如,我用 clang 得到“否”。)
关于c++ - C++ bool 函数的意外行为和不可能的返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987089/