c++ - C++ 'if' 语句中的变量赋值

标签 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。我在这里错过了什么?

最佳答案

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 中添加的。

关于c++ - C++ 'if' 语句中的变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60700205/

相关文章:

c++ - 在 Mathematica 中绘制来自 c++ 的二维点阵数据

c++ - 如何检查线程是否已在 C++11 及更高版本中完成工作?

c++ - 使用可变参数模板的递归元函数

c - 如何根据条件简洁地分配给结构的成员?

c++ - 如何使用小于 8 GB 的内存编译带有模板的余弦表?

c++ - Boost.Regex 与 C++11 正则表达式

c++ - 将 std::vector v 传递给需要在相应实例的整个生命周期内访问 v 的类的构造函数

Java - 为什么控制台上的输出为空?

java - 根据某些数组元素的状态更改按钮的颜色

c++ - 排序算法是否应该在比较函数中传递相同的元素