布尔函数总是 Return False

Boolean Function Always Return False

它必须为真,但函数 returns 为假。我不明白。怎么可能?

#include <iostream>
using namespace std;

bool Testing() {
    static int Variable = 0;

    if (Variable == 1) return true;
    else {
        Variable = 1;
        Testing();
    }

    return false;
}

int main()
{
    if (Testing()) cout << "True";
    else cout << "False";
}

main() 第一次调用 Testing() 时,会创建 static 变量并将其初始化为 0。因此 if 的计算结果为 false ,变量更新为 1,并且 Testing() 被第二次调用。和任何其他函数一样,该调用将 return 到调用它的地方。

在第 2 个 Testing() 运行 中,static 初始化被跳过,并且由于变量已经是 1,所以 if 计算为 true ,所以 true 得到 returned 给调用者,它在第一个 运行.

但是,不管第二个 运行 在内部做了什么,第一个 运行 内部的调用站点忽略了 returned 的 bool 值,因此流程继续正常进行,到达 return false; 语句,returning false 回到第一个 运行 的调用站点,它位于 main() 中。

bool Testing() {
    static int Variable = 0;

    if (Variable == 1)
        return true; // <-- 2nd run reaches here
    else {
                     // <-- 1st run reaches here
        Variable = 1;
        Testing();   // <-- 2nd function call made here
                     // <-- returns to here, but value is being ignored, so...
    }

    return false; // <-- 1st run reaches here, returns to main
}

要解决此问题,请在 Testing() 内更改此行:

Testing();

改为:

return Testing();

这样,当第二个运行 returns true时,第一个运行也会return true. main() will receive the finaltruethat the last recursive call toTesting()` returns.