Short answer
A declaration introduces a name and its type. Initialization gives that object its first value. Assignment stores a new value in an object that already exists. A variable can be declared without being initialized, and it can be assigned a value later.
Declaration: a name and a type
int score;
This line declares score as an int. Inside a function it also creates the variable, so it is a definition as well. It does not set a value. Reading score before it has a value is undefined behavior in C, so don’t do it.
Initialization: a starting value
int score = 90;
The = 90 part is the initializer. It gives score its starting value at the moment the variable is created. The = here is part of the declaration. It is not a separate step that happens later.
Assignment: a later value
int score; /* declaration: name and type */
score = 90; /* assignment: stores a new value */
Between these two lines, score holds an indeterminate value. The = operator used for assignment is covered in c assignment operators.
Side by side
This program uses all three steps:
#include <stdio.h>
int main(void) {
int a; /* declared, no value yet */
int b = 10; /* declared and initialized */
int c; /* declared, no value yet */
a = 5; /* assigned later */
c = 20; /* assigned later */
printf("%d %d %d\n", a, b, c); /* prints: 5 10 20 */
return 0;
}
Quick reference
| Term | What it does | Example |
|---|---|---|
| Declaration | Gives a name and a type | int score; |
| Definition | Creates the object, or provides the function body | int score; inside a function |
| Initialization | Gives the object its starting value as it is created | int score = 90; |
| Assignment | Stores a value in an object that already exists | score = 90; |
Inside a function, int score; is both a declaration and a definition. It is not an initialization, because it gives the variable no value.
Why the difference matters
- Local variables without a value. A local
intwith no initializer holds whatever bits were already in that memory. Reading it is a bug:
int main(void) {
int total;
total += 5; /* bug: total is read before it has a value */
return 0;
}
- Global and static variables. When no initializer is given, these start at zero. A
static int count;inside a function starts at 0, for example.
Common mix-ups
int x = 5;is not assignment. It is initialization. The=sign just looks like assignment.- Declaring is not zeroing. Only global and static variables get zero automatically. Local variables do not.
- Arrays cannot be assigned as a whole.
int a[3] = {1, 2, 3};initializes the array, buta = {1, 2, 3};later is an error. The brace list only works as an initializer.
Summary
- A declaration gives a name and a type.
- An initialization gives the object its starting value when it is created.
- An assignment stores a new value in an object that already exists.