Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

syntax

I am using 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++. 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

error: no semicolon at end of struct or union.

Why different error messages given by different implementations?

like image 613
Destructor Avatar asked May 05 '15 12:05

Destructor


1 Answers

The semicolon is required by both languages. Specifically, C specifies the declaration of one or more structure members as

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

and C++ specifies the declaration of one or more class member variables as

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. 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; in which case you could use -Werror to convert warnings into errors, if you'd prefer stricter diagnostics.

like image 174
Mike Seymour Avatar answered Sep 19 '22 23:09

Mike Seymour