Initialization gives an object an initial value when its definition is reached. The behavior differs between automatic objects and objects with static storage duration.
#include <stdio.h>
int global;
void test()
{
int automatic;
static int persistent;
printf("automatic = %d\n", automatic);
printf("persistent = %d\n", persistent);
}
int main()
{
int initialized = 10;
printf("initialized = %d\n", initialized);
printf("global = %d\n", global);
test();
return 0;
}
Example Output #
The values of uninitialized automatic objects are indeterminate, so automatic must not be read. The static objects are initialized to zero.
initialized = 10
global = 0
persistent = 0
Explanation #
An object can be initialized when it is defined:
int initialized = 10;
The object starts with the value 10.
An automatic object defined without an initializer:
int automatic;
has an indeterminate value. Reading such a value is generally not valid and can result in undefined behavior.
Objects with static storage duration that are not explicitly initialized are initialized to zero:
static int persistent;
The same applies to an uninitialized file-scope object:
int global;
Initialization Behavior #
| Object | Storage duration | No initializer |
|---|---|---|
| Local variable | Automatic | Indeterminate value |
static local variable |
Static | Initialized to zero |
| File-scope variable | Static | Initialized to zero |
| Dynamically allocated storage | Allocated | Indeterminate bytes returned by malloc() |
Initialization and assignment are different operations. Initialization occurs when an object is created, while assignment changes the value of an already existing object:
int number = 10; /* Initialization */
number = 20; /* Assignment */