以下包含 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
循环的文档,但也未能找到。
最佳答案
C 和 C++ 是不同的语言。 <iostream>
不是 C 库的一部分,且 using
和namespace
仅是 C++ 关键字。不要混合使用这些语言,因为它们根本不一样。
此外,正如 @sasquatch 提到的,在 C 中在 while
中声明变量是非法的。情况。
您不应该期望 C++ 代码能够在 C 中编译。您也不应该期望相反的方式,因为 C 不是 C++ 的正确子集。
关于c++ - 带有 While 循环的有效 C++ 代码的等效 C 代码无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147703/