【发布时间】:2015-07-20 18:41:33
【问题描述】:
以下包含 while 循环的代码在 C++ 中编译。
#include <iostream>
using namespace std;
int main() {
while (int i = 5)
{
break;
}
return 0;
}
但是,如果在 C 中编译,以下等效 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 循环的文档,但也找不到。
【问题讨论】:
-
Valid C++ code does not compile in C而且,那又怎样?有无数有效的 C++ 代码示例无法在 C 中编译。 -
我认为你不应该对这个问题投反对票。 C 和 C++ 通常混为一谈,因此您会混淆它们的特性是可以理解的。可能没有人再研究
C了,但是如果你熟悉C++,用不了一个小时就可以理解C子集是什么。 -
@PaulMcKenzie 如果您喜欢更好的标题,请继续更改它。别再恶心了!
-
@wallyk 感谢您的“支持”,如果您已经这样做了。
-
@lifebalance 我的评论是在您编辑问题以添加 C 代码之前发表的。如果您最初说“我有这个 C++ 代码,但我知道它不会编译为 C 代码,所以我在 C 中做了这个并且遇到了问题”,那么这将比您最初的未经编辑的帖子更有意义。
标签: c++ c while-loop syntax-error