Understanding the difference between Declaration and Definition in C
Difference between Declaration and Definition in C language
In C, understanding the difference between declaration and definition is crucial for effective memory management and code organization. Both play distinct roles in the compilation process and are essential for handling variables, functions, and other constructs in C.
Declaration:
- Purpose: A declaration introduces a variable, function, or type to the compiler without allocating memory or providing an implementation.
- Usage: Primarily used in header files or at the beginning of source files to inform the compiler about the existence of a symbol, such as a variable or function, before its actual definition.
Example of a declaration:
extern int x; // Declares an integer variable named 'x' defined elsewhere
int add(int a, int b); // Declares a function named 'add' defined later
Explanation:
- extern int x; tells the compiler that x is an integer variable defined elsewhere in the code (possibly in another file).
- int add(int a, int b); tells the compiler about the function add and its parameters but doesn’t provide its actual implementation.
Definition:
- Purpose: A definition allocates memory for a variable or provides the implementation of a function.
- Usage: Definitions are usually found in source files (.c files) where the actual code is implemented.
Example of a definition:
int x = 10; // Defines and initializes an integer variable named 'x' int add(int a, int b) { // Defines a function named 'add' return a + b; }
Explanation:
- int x = 10; allocates memory for x and initializes it to 10.
- The definition of add provides the actual code that performs the addition.
Example Code:
Let’s combine declaration and definition in a small program to illustrate the concept.
header.h (Declaration)
Code:
// Declarations
extern int x;
int add(int a, int b);
main.c (Definition)
Code:
#include <stdio.h>
#include "header.h"
// Definitions
int x = 10;
int add(int a, int b) {
return a + b;
}
int main() {
printf("x = %d\n", x);
printf("Sum = %d\n", add(x, 5));
return 0;
}
Output:
x = 10 Sum = 15
Explanation:
- Declaration in header.h: extern int x; and int add(int a, int b); tell the compiler about the existence of x and add, without defining them.
- Definition in main.c: int x = 10; and the add function’s code allocate memory and provide the function’s implementation.
Summary
- Declaration introduces the name and type but does not allocate memory or provide implementation.
- Definition allocates memory and/or provides the actual code.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming-exercises/c-snippets/difference-between-a-definition-and-a-declaration-in-c.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics