Alex Rivera | Logout

Declaration or Definition in C

Asked 2011-01-22T18:09:55.000
24

From External Variables Wiki:

If neither the extern keyword nor an initialization value are present, the statement can be either a declaration or a definition. It is up to the compiler to analyse the modules of the program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

int i;

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement: a. just a declaration, or b. declaration + definition?

Reference: Variable declaration and definition

Summary of answers received:

                         Declaration    Definition    Tentative Definition   Initialized 
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No


All definitions are declarations but not vice-versa.
Edit
Report

1 Answer

17

Assuming it's at file scope it's a 'tentative definition'. From 6.9.2/2 "External object definitions":

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

This means that it would be valid to also have the following in the translation unit:

int i = 42;

since that declaration has an explicit initializer, it's the definition of the variable i.

As far as if the declaration is in a block scope, the standard says the following (6.2.2/2 "Linkages of identifiers"):

Each declaration of an identifier with no linkage denotes a unique entity.

...

(paragraph 6) The following identifiers have no linkage: ... a block scope identifier for an object declared without the storage-class specifier extern.

So in block scope, the declaration would be a definition as well.

answered 2011-01-22T18:18:42.707

Your Answer