c++ - 为什么变量声明和for循环的条件一样好用?

标签 c++ for-loop language-lawyer declaration

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/

相关文章:

c++ - g++ 编译选项

使用字符串时 C++ 未知覆盖说明符

c++ - 强制 C++11 lambda 捕获变量

java - 使用扫描仪读取文本,存储在数组中并使用每个循环输出大写Java

python - 递归函数名称错误

c++ - 构造函数调用返回语句

c++ - 在默认初始化程序 gcc 与 clang 中使用 lambda

C++ STL streambuf异常处理

javascript - 如何使用 for 循环迭代 Angular $scope 变量

c++ - 未评估上下文中的默认模板参数和 lambda : bug or feature?