- 2074 Chaitra · 4 marks
Variable declaration versus definition
Short answer
A declaration introduces a variable’s or function’s name and type without allocating memory; it can appear multiple times. A definition allocates memory or gives the function body and occurs only once. For example, extern int x; is a declaration; int x = 10; is a definition.
What is the difference between variable declaration and variable definition? Explain with example.
A declaration tells the compiler the name and type of a variable or function, without necessarily allocating memory. A definition creates the entity: it allocates memory (and may give an initial value) or provides the function body.
| Declaration | Definition |
|---|---|
| Introduces name and type | Allocates memory / gives function body |
No memory is reserved (for extern and prototypes) | Memory is reserved |
| Can appear many times | Appears only once |
Example: extern int counter; | Example: int counter = 10; |
Example: int add(int, int); | Example: int add(int a, int b) { return a + b; } |
In C, int x; inside a function is both a declaration and a definition.
#include <stdio.h>
extern int counter; /* declaration only: no memory allocated here */
int add(int, int); /* function declaration (prototype) */
int counter = 10; /* definition: memory allocated, value given */
int main(void)
{
int x; /* declaration that is also a definition */
x = add(counter, 5);
printf("%d\n", x);
return 0;
}
int add(int a, int b) /* function definition */
{
return a + b;
}
Output:
15
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Declaration vs definition; C program structure · Computer Programming, chapter 3
- Why datatype in pointer declaration · Computer Programming, chapter 9
- Negative binomial: definition and difference · Probability and Statistics, chapter 2 · asked 4×
- Potential difference versus emf · Basic Electrical Engineering, chapter 1
- Fibonacci difference equation: closed form and limit · Digital Control System, chapter 2 · asked 2×
- Third-order difference equation: limit x(k+2)/x(k) · Digital Control System, chapter 2 · asked 2×