Q. What is the difference between variable declaration and variable definition in C programming language ?
Answer: This is one of the most confusing question that every beginner has in mind. Let me explain this with an example.
Consider the below statement:
This one is generally called as a variable declaration statement. But, strictly speaking, it is ‘variable declaration-cum-definition’. So what exactly is the difference between them. If we refer to Appendix A8 of “The C Programming Language” written by K & R, it clearly mentions that, “Any declaration that reserve storage is called definition”. It means, if, along with the declaration, if memory allocation is done with it, it is also called as a definition. In the above statement ‘int a’, we are informing the compiler that, the programmer needs to store a value of an integer type for which 4 bytes of memory should be allocated or reserved. Hence this statement is a declaration-cum-definition. Now another question arises in our mind – Is there anything known as “just declaration”. The answer is “Yes”. There is. For example, consider the below statement,
extern int a;
This statement is used to inform the compiler not to allocate/reserve any storage for the variable. It is just an indication to the compiler that, there could a variable named ‘a’ that is defined in any of the compilation units ( or any other module in the current project ) whose reference is used in the current context or file that is being compiled right now. Hence, if the compiler is unable to find its definition in the current file, the compiler should just ignore the usage of that variable in the current context without giving any compile time errors. So, by writing ‘extern int a’, compiler does not reserve storage for ‘a’, as it understands that, memory allocation is done somewhere else and only the referencing is done in the current context. This above statement is called purely as ‘variable declaration’.
In simple words,
Variable Definition: Bring in the scope and reserve storage. Example: ‘int a’
Variable Declaration: Only bring in the scope and memory not reserved. Example: ‘extern int a’
Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.
Learn from the best embedded system training institute in India.