๐ C Declaration and Definition – Variables and Functions Explained
In C programming, declaration and definition are two fundamental concepts that are often misunderstood. Letโs simplify them:
๐น Declaration
A declaration tells the compiler about the name and type of a variable or function, but it does not allocate memory (for variables) or contain actual code (for functions).
๐น Definition
A definition not only declares but also allocates memory (for variables) or provides the implementation (for functions).
๐ Example 1: Variable Declaration vs Definition
Here, the declaration happens first, then the definition with initialization.
// Declaration extern int num; // Definition int num = 10;
๐ Example 2: Function Declaration and Definition
We declare the function at the top and define it later in the program.
#include <stdio.h> // Function declaration void sayHello(); int main() { sayHello(); // Function call return 0; } // Function definition void sayHello() { printf("Hello from the function!\n"); }
๐ง Important Notes
extern
is used to declare a variable without defining it.- A declaration can appear multiple times, but a definition must appear only once.
- Function prototypes are declarations.
๐ฏ Summary
- Declaration: Announces the name and type.
- Definition: Actually creates the object or implements the function.
๐ก Tip Time!
Use declarations to organize code across files and definitions to actually get things done. Try declaring variables or functions in a header file and defining them in a source file.