What is the Difference Between Declaration and Definition in C?

🆚 Go to Comparative Table 🆚

The main difference between declaration and definition in C lies in the information provided and the memory allocation.

  • Declaration: A declaration provides basic information about a variable, function, or class, such as its name and type. It does not allocate memory for the variable or function. For example, when declaring a function without providing its body, the compiler is informed about the existence of the function and its parameters but does not allocate storage for it.
  • Definition: A definition, on the other hand, provides all the necessary details about a variable, function, or class, including its type, name, and value or function body. Memory is allocated during the definition process. For instance, when defining a function with its body, the system allocates memory for the function and associates an identifier with it.

In summary:

Declaration Definition
Just provides information about a variable or function (name, type) Provides all necessary details about a variable or function (name, type, value or body)
Does not allocate memory Allocates memory
Examples: int x; (variable declaration), int f(int); (function declaration) Examples: int x = 5; (variable definition), `int f(int a){ return a; } (function definition)

A variable or function can be declared multiple times, but it can be defined only once.

Comparative Table: Declaration vs Definition in C

The difference between declaration and definition in C is as follows:

Declaration Definition
Provides information about the name and type of a variable or function. Allocates memory for the variable or function.
Introduces a name in a given scope. Defines the properties and behavior of a variable or function.
Can be repeated in a given scope. Can be defined only once.
Example: int a; - declares a variable a with the type int. Example: int a = 10; - defines a variable a with the type int and initializes it with the value 10.
Does not allocate memory. Allocates memory.

In C, a declaration merely provides information that a function or variable exists and gives its type, while a definition allocates memory for the variable or function and provides all the necessary details.