Every variable must be declared before it can be used. The declaration determines the variable's type, its storage class, and possibly its initial value. The type of a variable determines how much space it occupies in storage and how the bit pattern it stores is interpreted. For example:
float dollars = 2.5F; // a variable of type float
The variable dollars designates a region in memory with a size of 4 bytes. The contents of these four bytes are interpreted as a floating-point number, and initialized with the value 2.5.
The storage class of a variable determines its scope, its storage duration, and its linkage. The scope can be either block or file (see Section 1.2.4, earlier in this book). Variables also have one of two storage durations:
The variable is generated and initialized once, before the program begins. It exists continuously throughout the execution of the program.
Automatic storage duration
The variable is generated anew each time the program flow enters the block in which it is defined. When the block is terminated, the memory occupied by the variable is freed.
The storage class of a variable is determined by the position of its declaration in the source file and by the storage class specifier, if any. A declaration may contain no more than one storage class specifier. Table 1-18 lists the valid storage class specifiers.
Table 1-19 illustrates the possible storage classes and their effect on the scope and the storage duration of variables.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression. Some examples are:
int index = 0, max = 99, *intptr = NULL;
static char message[20] = "Example!";
Variables are not initialized in declarations that do not cause an object to be created, such as function prototypes and declarations that refer to external variable definitions.
Every initialization is subject to the following rules:
1. A variable declaration with an initializer is always a definition. This means that storage is allocated for the variable.
2. A variable with static storage duration can only be initialized with a value that can be calculated at the time of compiling. Hence the initial value must be a constant expression.
3. For declarations without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined!
The type conversion rules for simple assignments are also applied on initialization.