C++ 中嵌套 If 的行为是什么?

0 c++ if-statement

#include <iostream>
using namespace std;
int main()
{
    int a = 1;
    int b = 2;
    if(a > 0)
    {
        cout << "we are in the first" << endl;
        if(b > 3)
        {
            cout << "we are in the second" << endl;
        }
    }
    else
    {
        cout << "we are in else" << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

根据 C++ISO:

在 if 语句的第二种形式(包括 else 的形式)中,如果第一个子语句也是 if 语句,则该内部 if 语句应包含 else 部分。换句话说,else 与最近的 un-elsed if 相关联。

我认为上面的代码会打印出“we are in else”,因为最近的 un-elsed 的条件if(内部条件)导致 false。我错过了什么?

Yks*_*nen 5

该标准在这里谈论无块语句。在这样的情况下:

if (a > 0)
    if (b > 3) std::cout << "nested-if\n";
    else std::cout << "nested-else\n";
Run Code Online (Sandbox Code Playgroud)

else是嵌套的一部分if。这些东西在标准中必须是明确的,但我强烈建议{}在每种情况下使用块语句(包含在 中)以防止混淆。