使用While循环的有效C ++代码的等效C代码不会编译 [英] The equivalent C code of a valid C++ code with a While loop does not compile

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

问题描述

以下代码包含 while 循环在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;
}



<

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中查找 while 循环的文档,但是还没有找到它。

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:


条件 - 可以上下文转换为
的任何表达式 bool 或code初始化程序的单个变量的声明。这个表达式在每次迭代之前被评估,
如果产生false,则退出循环。如果这是一个声明,
初始化程序在每次迭代之前被评估,如果
的值被声明的变量转换为false,则退出循环。

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 中,在<$ c $的每次迭代之前测试表达式 c> while 循环。 参考的逐字:

Whereas in C, an expression is tested for before each iteration of a while loop. Verbatim from the C reference:


表达式 - 标量类型的任何表达式。这个表达式是在每次迭代之前评估的
,如果它等于 zero
,则退出循环。

expression - any expression of scalar type. This expression is evaluated before each iteration, and if it compares equal to zero, the loop is exited.

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

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