Lazar Lazar - 1 month ago 5
C Question

Declaration and definition confusion in C

This answer confused me.

If we have two lines in same .c file:

extern int c;
int c;



  • How is the first line of code a declaration and second a definition?

  • Aren't both declarations?

  • How these two lines differ?


Answer
int i; // Declare & Define
int main()
{
    i = 5;
}

Here int i; both declares and defines the variable. It effectively says, create a variable named i, of type int. Also, the storage for the variable is that it is a global variable defined in the object file associated with this source file.

extern int i; // Only Declare. When Compile code, We get the compilation error.
int main()
{
    i = 5;
}

Here extern is creating a declaration of a variable but NOT defining it; it is saying that the storage for the variable is somewhere else.

extern int i; // Dclare

int main()
{
    // code
}
int i = 5; // Define

And now you have a declaration of i at the top of the program and a definition at the bottom.

Comments