在 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/