When initializing scalar types, the value of the assignment-expression is assigned to the variable. The conversion rules for assignment apply. (See Type Conversions in Chapter 4 for information on conversion rules.)
Syntax
declaration :
declaration-specifiers init-declarator-list opt ;
declaration-specifiers :
storage-class-specifier declaration-specifiers opt
type-specifier declaration-specifiers opt
type-qualifier declaration-specifiers opt
init-declarator-list :
init-declarator
init-declarator-list , init-declarator
init-declarator :
declarator
declarator = initializer /* For scalar initialization */
initializer :
assignment-expression
You can initialize variables of any type, provided that you obey the following rules:
Examples
The following examples illustrate initializations:
int x = 10;
The integer variable x
is initialized to the constant expression 10
.
register int *px = 0;
The pointer px
is initialized to 0, producing a “null” pointer.
const int c = (3 * 1024);
This example uses a constant expression (3 * 1024)
to initialize c
to a constant value that cannot be modified because of the const keyword.
int *b = &x;
This statement initializes the pointer b
with the address of another variable, x
.
int *const a = &z;
The pointer a
is initialized with the address of a variable named z
. However, since it is specified to be a const, the variable a
can only be initialized, never modified. It always points to the same location.
int GLOBAL ;
int function( void )
{
int LOCAL ;
static int *lp = &LOCAL; /* Illegal initialization */
static int *gp = &GLOBAL; /* Legal initialization */
register int *rp = &LOCAL; /* Legal initialization */
}
The global variable GLOBAL
is declared at the external level, so it has global lifetime. The local variable LOCAL
has auto storage class and only has an address during the execution of the function in which it is declared. Therefore, attempting to initialize the static pointer variable lp
with the address of LOCAL
is not permitted. The static pointer variable gp
can be initialized to the address of GLOBAL
because that address is always the same. Similarly, *rp
can be initialized because rp
is a local variable and can have a nonconstant initializer. Each time the block is entered, LOCAL
has a new address, which is then assigned to rp
.