tags:

views:

449

answers:

5

In a C++ class declaration:

class Thing
{
    ...
};

why must I include the semicolon?

+10  A: 

Because the language grammar says so...

Maximilian Mayerl
You are gonna get your first nice answer badge for this... :)
Amarghosh
comon vote for this answer like crazy
Pieter888
why is this voted up? Why is the sky blue? ... because it's not red, duh! Seriously vote this down.
caspin
Great analogy, Caspin. Not sure why so many people think this is useful. Next time you upvoters wonder why something is the way it is, just repeat the question as your answer and there you go!
GMan
@Caspin: how can anyone answer this? Its the choice of the language designer. OK, heres another: why do you have to end a ruby function with the "end" keyword? There is no *good* reason on earth besides the fact that that is what the language designer chose to do. If you don't like it that much find another language!
jkp
Look at John's answer to see what a useful answer to this question looks like.
sepp2k
+6  A: 

because you can optionally declare objects

class Thing
{
    ...
}instanceOfThing;

for historical reasons

jk
+37  A: 

The full syntax is, essentially,

class NAME { constituents } instances ;

where constituent-sequence is the sequence of class elements and methods, and instance-sequence is a comma-separated list of instances of the class.

Example:

class FOO {
  int bar;
  int baz;
} waldo;

declares both the class FOO and an object waldo.

The instance sequence may be empty, in which case you would have just

class FOO {
  int bar;
  int baz;
};

You have to put the semicolon there so the compiler will know whether you declared any instances or not.

This is a C compatibility thing.

John R. Strohm
Doesn't even need the name or constituents: `class { } waldo;` is legal.
MSalters
+1 I learned something new.
StackedCrooked
A: 

Because it could be a definition of the next element. For example, taking it from C syntax: if you declare

struct { ... } main (int argc, char..

then it assumes main returns a struct. If there was a semicolon,

struct { ... }; main (int argc, char..

then main returns an int.

lorenzog
C++ language has no "implicit int" rule. Your second variant is simply incorrect.
AndreyT
+1  A: 

A good rule to help you remember where to put semicolons:

  • If it's a definition, it needs a semicolon at the end. Classes, structs and unions are all information for the compiler, so need a trailing ; to mark no declared instances.
  • If it contains code, it doesn't need a semicolon at the end. If statements, for loops, while loops and functions contain code, so don't need a trailing ;.

Namespaces also don't require a trailing semicolon, because they can contain a mix of both the above (so can contain code, so don't need a semicolon).

AshleysBrain