Search code examples
cvariablesmemory-managementdefinitionvariable-declaration

Difference between variable declaration and definition in C. When does the memory gets allocated?


So I have been trying to learn C on my own. So just a couple of videos and articles and a a book by my side. Although it sounds like a simple concept (I'm sure it is), I dnt think the concept is clear to me.

Can you please quote an example when a variable is declared or defined?(together and separately)

Like in some articles or forums I read they say

Int x; ( x is declared)

Somewhere it's written

Int x; ( x is defined).

When will the memory be allocated to the variable? Again somewhere it is said that variable has to be defined first to get memory allocated and somewhere it's said it is allocated when a variable is declared?


Solution

  • Like in some articles or forums I read they say Int x; ( x is declared) Somewhere it's written Int x; ( x is defined).

    Actually the int x; declares and defines it at the same time so both are valid but incomplete.

    The declaration shows the compiler the type of variable without creating it.

    extern int x; // <- this is declaration
    

    Definition creates the the object, if the object was declared before its definition must match the declaration.

    extern int x;
    int x;
    

    Is valid but

    extern int x;
    double x; 
    

    is not.