像 int i = 5
这样的声明的返回值/类型是什么?
为什么不编译这段代码:
#include <iostream>
void foo(void) {
std::cout << "Hello";
}
int main()
{
int i = 0;
for(foo(); (int i = 5)==5 ; ++i)std::cout << i;
}
虽然这样做
#include <iostream>
void foo(void) {
std::cout << "Hello";
}
int main()
{
int i = 0;
for(foo(); int i = 5; ++i)std::cout << i;
}
最佳答案
for循环要求 condition 是表达式或声明:
condition - either
- an expression which is contextually convertible to bool. This expression is evaluated before each iteration, and if it yields false, the loop is exited.
- a declaration of a single variable with a brace-or-equals initializer. the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.
第一个代码不起作用,因为 (int i = 5)==5
不是有效的 expression一点也不。 (也不是声明。) operator==
的操作数也应该是表达式,但 int i = 5
是声明,而不是表达式。
第二个代码有效,因为 int i = 5
匹配 condition 的第二个有效案例;使用 equals 初始化器声明单个变量。 i
的值会被转换成 bool
进行判断;总是5
,然后导致无限循环。
关于c++ - 为什么变量声明和for循环的条件一样好用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39992781/