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

时间:2020-03-16 04:05:55

标签: c++ c++11 if-statement c++17 variable-assignment

在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;
                                    ^

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

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。我在这里想念什么?

2 个答案:

答案 0 :(得分:6)

if ((int i=5) == 5)是一个语法错误,它与if语句所支持的任何语法都不匹配。语法为 init-statement(可选)condition ,其中 condition 可以是表达式,也可以是带有初始化程序的声明,您可以阅读有关语法{{3 }}。

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

答案 1 :(得分:2)

对于初学者来说,我相信您的编译器是拒绝的权利

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

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

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