c++ - 带有 While 循环的有效 C++ 代码的等效 C 代码无法编译

标签 c++ c while-loop syntax-error

以下包含 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 库的一部分,且 usingnamespace仅是 C++ 关键字。不要混合使用这些语言,因为它们根本不一样。

此外,正如 @sasquatch 提到的,在 C 中在 while 中声明变量是非法的。情况。

您不应该期望 C++ 代码能够在 C 中编译。您也不应该期望相反的方式,因为 C 不是 C++ 的正确子集。

关于c++ - 带有 While 循环的有效 C++ 代码的等效 C 代码无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147703/

相关文章:

c++ - 如何获取字符串的一部分

c链表删除函数

bash:在 while 循环中剪切时保留白色字符

c++ - 与主线程相比,辅助线程崩溃是否有优势?

javascript - 如何从 WebAssembly 模块中检测浏览器信息?

c - 使用 autotools 时原始 .h 文件会发生什么情况?

c++ - While循环什么时候使用OR或AND?

c++ - 在没有外部库的情况下正确地将 utf-16 文本文件读入字符串?

c++ - 将 std::bitset 分成两半?

python - 如何循环整个 python 脚本以及每次运行更改顺序