一个有效的C ++ code与While循环的等效C code不编译 [英] The equivalent C code of a valid C++ code with a While loop does not compile
问题描述
包含,而
循环下code编译在C ++中。
The following code containing a while
loop compiles in C++.
#include <iostream>
using namespace std;
int main() {
while (int i = 5)
{
break;
}
return 0;
}
不过,如果用C编译如下出错等价的C code的结果:
However, the following equivalent C code results in an error if compiled in C:
#include <stdio.h>
int main() {
while (int i = 5)
{
break;
}
return 0;
}
编译器的输出:
> prog.c: In function 'main': prog.c:5:9: error: expected expression
> before 'int' while (int i = 5)prog.c: In function 'main':
> prog.c:5:9: error: expected expression before 'int' while (int i =
> 5)
为什么会出现这种情况?我试图来查找在C ,而
循环的文件,但一直没能找到,要么。
Why does this happen? I tried to look up the documentation for the while
loop in C, but haven't been able to locate that either.
推荐答案
在 C ++ ,一个条件
是的每次迭代之前测试,而
循环。逐字从 C ++参考A>:
In C++, a condition
is tested for before each iteration of a while
loop. Verbatim from the C++ reference:
条件
- 任何Ex pression这是上下文转换为
布尔
或声明
用大括号或-等于单个变量
初始化。每次迭代之前该前pression进行评估,并
如果它产生假,则退出循环。如果这是一个声明中,
每次迭代之前初始化被评估,并且如果该值
声明的变量转化为假,则退出循环。
condition
- any expression which is contextually convertible tobool
or adeclaration
of a single variable with a brace-or-equals initializer. This expression is evaluated before each iteration, and if it yields false, the loop is exited. If this is a declaration, the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.
而在 C ,一个前pression
是一个,而每次迭代前测试code>循环。从 C基准逐字:
Whereas in C, an expression
is tested for before each iteration of a while
loop. Verbatim from the C reference:
前pression
- 标量的任何Ex pression
键入。这当然pression是
每次迭代之前评估,如果把它比等于零
,
退出循环。
expression
- any expression ofscalar
type. This expression is evaluated before each iteration, and if it compares equal tozero
, the loop is exited.
这篇关于一个有效的C ++ code与While循环的等效C code不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!