Reputation: 37
In the following statements first three are definitions and the last one is the declaration:
auto int i;
static int j;
register int k;
extern int l;
What's the reason for the same?
Upvotes: 0
Views: 50
Reputation:
I assume the question is about the terms declaration and definition in C.
A declaration tells the compiler name and type of "something".
A definition is a declaration, but additionally "creates" the "something" that is declared. E.g. for a variable, this would introduce some storage space for this variable.
In your first three examples, the variables are actually created. The storage classes auto
, static
and register
all just specify a storage duration. In contrast, the storage class extern
tells the compiler that this variable is known, but it might exist in a different translation unit.
Maybe an example comparing the declaration and definition of functions will make the concept easier to understand:
// function declaration:
int foo(int x);
// (now we know a function foo should be "somewhere", but it doesn't exist yet)
// function definition:
int foo(int x) {
return x+1;
}
Upvotes: 1
Reputation: 76
In first three(int i, static int j, register int k) is a definition. It denotes the space for the integer to be in this translation unit and advices the linker to link all references to i against this entity. If you have more or less than exactly one of these definitions, the linker will complain.
But in last extern int l, is a declaration, since it just introduces/specifies l, no new memory address/space is allocated. You can have as many extern int l in each compilation unit as you want. A declaration introduces names into a translation unit or redeclares names introduced by previous declarations.
Upvotes: 1