Initializers
Declarators can specify the initial value for objects. The only way to specify a value for objects of const type is in the declarator. The part of the declarator that specifies this initial value is called the initializer. There are two fundamental types of initializers:
Initializers invoked using the equal-sign syntax, including aggregate initializers:
= expression = { expression-list } = { { expression-list}, {expression-list}, . . . }
Initializers invoked using function-style syntax:
( expression )
Only objects of classes with constructors can be initialized with the function-style syntax. The two syntax forms also differ in access control and in the potential use of temporary objects. Consider the following code, which illustrates some declarators with initializers:
int i = 7; // Uses equal-sign syntax.
Customer Cust( "Taxpayer, Joe", // Uses function-style
"14 Cherry Lane", // syntax. Requires presence
"Manteca", // of a constructor.
"CA" );
Declarations of automatic, register, static, and external variables can contain initializers. However, declarations of external variables can contain initializers only if the variables are not declared as extern.
These initializers can contain expressions involving constants and variables in the current scope. The initializer expression is evaluated at the point the declaration is encountered in program flow, or, for global static objects and variables, at program startup. (For more information about initialization of global static objects, see Additional Startup Considerations.)
Topics in this section: