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

Tes*_*a J 3 c++ if-statement variable-assignment c++11 c++17

在 C++ 中,以下是有效的,我可以毫无问题地运行它

int main(){
    if (int i=5)
        std::cout << i << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

if ((int i=5) == 5)
    std::cout << i << std::endl;
Run Code Online (Sandbox Code Playgroud)

错误:

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;
                                    ^
Run Code Online (Sandbox Code Playgroud)

此外,在 c++17 下面的代码也必须有效,但它再次给我一个类似的错误

if (int i=5; i == 5)
    std::cout << i << std::endl;
Run Code Online (Sandbox Code Playgroud)

错误:

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)
                  ^
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用g++ test.cpp -std=c++17. g++ --version给我g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609。我在这里缺少什么?

M.M*_*M.M 6

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

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