Skip to main content

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.

DeclarationDefinition
Introduces name and typeAllocates memory / gives function body
No memory is reserved (for extern and prototypes)Memory is reserved
Can appear many timesAppears 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)

All Computer Programming chapter 3 questions →