没有分号的程序在 C 中编译得很好,而不是在 C++ 中为什么?

Program without semicolon compiles fine in C not in C++ why?

我正在使用 Orwell Dev C++ IDE。最近我测试了一个简单的程序,其中我忘记了分号 (;) 但它仍然可以在 C 中正常编译,但在 C++ 中却不行。为什么?这是什么原因?

// C program compiles & runs fine, even ; missing at end of struct
#include <stdio.h>
struct test
{ int a,b};     // missing semicolon
int main()
{
    struct test d={3,6};
    printf("%d",d.a);
    return 0;
}

[Warning] no semicolon at end of struct or union [enabled by default]

// Following is compilation error in C++
#include <stdio.h>
struct test
{ int a,b};     // missing semicolon
int main()
{
    struct test d={3,6};
    printf("%d",d.a);
    return 0;
}

[Error] expected ';' at end of member declaration

我也在代码块 13.12 中尝试了相同的 C 程序 IDE 但它显示以下错误消息

error: no semicolon at end of struct or union.

为什么不同的实现给出不同的错误信息?

两种语言都需要分号。具体来说,C 指定一个或多个结构成员的声明为

struct-declaration:
    specifier-qualifier-list struct-declarator-list ;

和C++指定一个或多个class成员变量的声明为

member-declaration:
    attribute-specifier-seq<opt> decl-specifier-seq<opt> member-declarator-list<opt> ;

两者的结尾都需要一个分号。

您将不得不问编译器作者为什么他们的 C++ 编译器比他们的 C 编译器更严格。请注意,语言规范仅在程序格式错误时才需要 "diagnostic",因此发出警告并继续编译(就好像存在分号)或发出错误并停止都是合法的。

看起来您的 IDE 正在使用 GCC 作为其编译器;在这种情况下,如果您更喜欢更严格的诊断,您可以使用 -Werror 将警告转换为错误。