一个有效的C ++ code与While循环的等效C code不编译 [英] The equivalent C code of a valid C++ code with a While loop does not compile

查看:208
本文介绍了一个有效的C ++ code与While循环的等效C code不编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

包含,而循环下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 ++参考

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 to bool or a declaration 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 是一个,而循环。从 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 of scalar type. This expression is evaluated before each iteration, and if it compares equal to zero, the loop is exited.

这篇关于一个有效的C ++ code与While循环的等效C code不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆