Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shall a C++ class function end with a }; or only a }?

Tags:

c++

syntax

A basic questions about C++ syntax.

Shall a c++ function end with a ; or does it not matter?

Or what is the difference between those two examples?

With a ending ;

void Test :: print()
{
  ...
};

Without ;

void Test :: print()
{
  ...
}

I have seen C++ code both with and without, but I don't get the difference.

/Thanks


Update:

In this case the ; should be avoided since it is not doing anything useful and may even become a problem in the future.

like image 427
Johan Avatar asked Mar 30 '11 14:03

Johan


2 Answers

Outside of a class body (where a function definition may optionally be followed by a single ;), a function definition is terminated by the end of a compound-statement - that is the closing }. At namespace scope, the next token after the closing brace of a function-definition must form part of the next declaration.

In C++03, there is no such thing as an empty-declaration so placing a ; is illegal, although accepted by many implementations. (Although the syntax of a C++03 simple-declaration appears to allow a missing decl-specifier-seq and a missing init-declarator-list, leaving just a ;, there is a semantic rule forbidding both optional parts to be left out expressed in 7 [dcl.dcl] / 3 of the standard.)

In a simple-declaration, the optional init-declarator-list can be omitted only when declaring a class (clause 9) or enumeration (7.2), that is, when the decl-specifier-seq contains either a class-specifier, an elaborated-type-specifier with a class-key (9.1), or an enum-specifier.

C++0x introduces an empty-declaration (which is a declaration with no effect), so you can have as many rogue ; at namespace scope as you like although there is no good reason to do so.

like image 73
CB Bailey Avatar answered Nov 05 '22 03:11

CB Bailey


You are indeed adding empty declarations to your file when you put in spurious semicolons. It does not matter much, as @Space_C0wb0y pointed out.

BTW, the heading does not fit your question.

like image 42
Michael Piefel Avatar answered Nov 05 '22 04:11

Michael Piefel