Declarations

Before a name (identifier) can be used in a C++ program, it must be declared or defined.

A declaration states the type and name of an entity, but does not cause memory to be allocated for the storage of the entity. Thus, a declaration merely states that an entity exists (and is defined somewhere else). Declaring an entity multiple times is legal (and often necessary).

A declaration that also defines an entity for the name to which it refers is a definition. There must be exactly one definition for each name in a C++ program. For variables, a declaration is also a definition unless it is preceded by the keyword extern.

Here are some legal variable declarations:

extern int i;
extern int i; // legal re-declaration
extern bool isGood;

The keyword extern means that the following object is defined somewhere else.

Here are some legal variable declarations that are also definitions:

int j, k; // j and k are both defined as int
char c;
bool isBad = false;

Here is an illegal variable declaration:

extern float f;  // ok---next line is illegal
extern double f; // illegal---type mismatch

The second declaration is illegal because the identifier f has already been declared.

Here are some illegal variable definitions:

char m = 'm'; // ok---next 2 lines are illegal
char m;       // illegal---re-definition
int m;        // illegal---re-definition

The last two definitions are illegal because the identifier m has already been declared (and defined).


Burton Ma
Department of Computing and Information Science
Queen's University