Microsoft Interview Question
In C declaration is just declaring a variable at the beginning of the program
eg; int i;
And definition is assigning a value ie, intialisation
eg; int i=5;
Hop this is r8....
writing just int i has allocated the required 2 bytes or 4 bytes. So that has defined the variable.
This is a topic that has created a lot of confusion in internet forums. Let me put it clear here. Reply me, if you don't understand after reading this.
- Metallicatony September 11, 2008Declaration and definition have different meanings in different contexts. Generally, a declaration describes to the compiler to bind an identifier with a specific data type. Compiler does NOT allocate storage when it sees a declaration.
A definition tells the compiler to allocate storage for the declared data type.
Function Declaration vs Definition
----------------------------------
Declaration of a function means telling to the compiler about the function's name, arguments and return type. This is done by the prototype of the function.
Eg:
int func(int x, float y) ();
Definition of a function means telling to the compiler about the details of a function and what it should do when the function is called. This is when, compiler allocates storage.
Eg:
int func(int x, float y) {
char response;
int value;
....
....
return value;
}
Variable Declaration vs Definition
----------------------------------
For automatic, static & register storage class variables, declaration and definition are the same. There is no difference between both terms. By that, I mean, the binding of identifier with data type and allocation of storage will happen at the same time.
But, when it comes to an extern variable, their meaning differ. For example, when you write
extern int i; /* extern declaration of i */
it WONT allocate storage. It tells to the compiler that a variable called "i" of integer type has already been defined (binding int data type with variable "i" and allocating space for it) in some other file. So, connect me to that memory. This is basically a linking process and is taken care by the linker.
Thus definition and declaration hold different meaning, when it comes to extern storage class variables.