Difference between Definition and Declaration ?


  •  Declaration of a variable is for informing to the compiler the following information: name of the variable, type of value it holds and the initial value if any it takes. i.e., declaration gives details about the properties of a variable. Whereas, Definition of a variable says where the variable gets stored. i.e., memory for the variable is allocated during the definition of the variable.
  • In C language definition and declaration for a variable takes place at the same time. i.e. there is no difference between declaration and definition. For example, consider the following declaration

int a;

  • Here, the information such as the variable name: a, and data type: int, which is sent to the compiler which will be stored in the data structure known as symbol table. Along with this, a memory of size 2 bytes(depending upon the type of compiler) will be allocated.
  • Suppose, if we want to only declare variables and not to define it i.e. we do not want to allocate memory, then the following declaration can be used

extern int a;

  • In this example, only the information about the variable is sent and no memory allocation is done. The above information tells the compiler that the variable a is declared now while memory for it will be defined later in the same file or in different file.
  • Declaration of a function provides the compiler the name of the function, the number and type of arguments it takes and its return type. For example, consider the following code,
int add(int, int);
  • Here, a function named add is declared with 2 arguments of type int and return type int. Memory will not be allocated at this stage.
  • Definition of the function is used for allocating memory for the function. For example consider the following function definition,

int add(int a, int b)

  {

    return (a+b);

  }

  • During this function definition, the memory for the function add will be allocated. A variable or a function can be declared any number of times but, it can be defined only once.

Content Source : GeeksforGeeks

Useful Links : Understanding “extern” keyword in C