What is the difference between Definition and Declaration of a variable? Am not talking about function, but variable.
When I googled, I found these two answers which are quite contradictory! While one says "definition occures once through the program( memory is allocated once ), but the declaration can occur many times.", the other says "This means that the declaration is only one throughout the program but definitions can be many."
Answer 1:
definition defines the memory area ( allocates the memory ) for the variable and the declaration tells about the signature of the variable ( type and size to be considered). definition occures once through the program( memory is allocated once ), but the declaration can occur many times.
OR For a variable, the definition is the statement that actually allocates memory. For example, the statement:
is a definition. On the other hand, an extern reference to the same variable:
extern long int var;
is a declaration, since this statement doesn't cause any memory to be allocated. Here's another example of a declaration:
typedef MyType short;
Answer 2
Declaration can come only once and definition can come many times in the program.
Let's take an example,
Line 1: #include<stdio.h>
Line 2:
Line 3: void main()
Line 4: {
Line 5: int x; //declaration
Line 6:
Line 7: x=10; //definition
Line 8: }
In the above program, on the line 5 what appears is declaration and on line 7 the definition is there.
Now if we declare the variable x again in the program we will get the error saying that the variable is already declared.
Whereas if we assign some new value to variable x, say 20
i.e.
x=20;
this is totally fine and we can assign any number of values in the same program. This means that the declaration is only one throughout the program but definitions can be many.
Can anyone give me the proper answer?
Thank-you in advance.