简体   繁体   English

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

[英]Program without semicolon compiles fine in C not in C++ why?

I am using Orwell Dev C++ IDE. 我正在使用Orwell Dev C ++ IDE。 Recently I tested following simple program in which I forgot to put semicolon ( ; ) but still it compiles fine in C but not in C++. 最近我测试了以下简单的程序,其中我忘了放分号( ; )但它仍然在C中编译好但在C ++中没编译。 Why? 为什么? What is the reason? 是什么原因?

// 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 在会员声明结束时

I also tried same C program in codeblocks 13.12 IDE but it shows following error message 我也尝试在代码块13.12 IDE中使用相同的C程序,但它显示以下错误消息

error: no semicolon at end of struct or union. 错误:结构或联合结束时没有分号。

Why different error messages given by different implementations? 为什么不同的实现给出不同的错误消息?

The semicolon is required by both languages. 两种语言都需要分号。 Specifically, C specifies the declaration of one or more structure members as 具体而言,C指定一个或多个结构成员的声明为

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

and C++ specifies the declaration of one or more class member variables as 和C ++指定一个或多个类成员变量的声明

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

both of which require a semicolon at the end. 两者都需要一个分号。

You'll have to ask the compiler writers why their C++ compiler is more strict than their C compiler. 你必须要求编译器编写者为什么他们的C ++编译器比他们的C编译器更严格。 Note that the language specifications only require a "diagnostic" if a program is ill-formed, so it's legitimate either to issue a warning and continue compiling as if the semicolon were present, or to issue an error and stop. 请注意,如果程序格式错误,语言规范只需要“诊断”,因此发出警告并继续编译就像分号存在一样,或发出错误并停止是合法的。

It looks like your IDE is using GCC as its compiler; 看起来您的IDE使用GCC作为其编译器; in which case you could use -Werror to convert warnings into errors, if you'd prefer stricter diagnostics. 在这种情况下,如果您更喜欢更严格的诊断,可以使用-Werror将警告转换为错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM