【发布时间】:2020-06-27 05:24:13
【问题描述】:
在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。我在这里错过了什么?
【问题讨论】:
-
@FoggyDay 是的,您可以在 if 条件中声明一个变量。试试吧。
if(int i=5)工作。
标签: c++ c++11 if-statement c++17 variable-assignment