C++ if语句中的变量赋值

Variable assignment inside C++ if statement

在 c++ 中,以下是有效的,我可以 运行 它没有问题

int main(){
    if (int i=5)
        std::cout << i << std::endl;
    return 0;
}

但是,即使以下内容也应该有效,但它给了我一个错误

if ((int i=5) == 5)
    std::cout << i << std::endl;

错误:

test.cpp: In function ‘int main()’:
test.cpp:4:10: error: expected primary-expression before ‘int’
     if ((int i=5) == 5)
          ^
test.cpp:4:10: error: expected ‘)’ before ‘int’
test.cpp:5:36: error: expected ‘)’ before ‘;’ token
         std::cout << i << std::endl;
                                    ^

此外,在下面的代码 must be valid 中的 c++17 中也是如此,但它再次给了我一个类似的错误

if (int i=5; i == 5)
    std::cout << i << std::endl;

错误:

test.cpp: In function ‘int main()’:
test.cpp:4:16: error: expected ‘)’ before ‘;’ token
     if (int i=5; i == 5)
                ^
test.cpp:4:18: error: ‘i’ was not declared in this scope
     if (int i=5; i == 5)
                  ^

我正在尝试使用 g++ test.cpp -std=c++17 进行编译。 g++ --version 给我 g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609。我在这里错过了什么?

if ((int i=5) == 5) 是语法错误,它不匹配 if 语句的任何支持语法。语法是 init-statement(optional) condition ,其中 condition 可以是表达式,也可以是带有初始化程序的声明,您可以阅读更多详细信息关于语法 on cppreference.

if (int i=5; i == 5) 是正确的,但是您使用的是旧版本的 gcc,该版本可追溯到 C++17 标准化之前。您需要升级编译器版本。根据 C++ Standards Support in GCC,此功能已添加到 GCC 7 中。

对于初学者,我相信你的编译器拒绝是对的

if ((int i=5) == 5)

因为这不是合法的 C++ 代码。变量声明语句不是表达式,因此不能将 (int i = 5) 视为表达式。

对于第二个,我怀疑你只需要更新你的编译器。 g++ 5.6 目前是一个相当旧的版本,我相信 g++ 的更多更新版本将毫无问题地处理该代码。