7.5 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.”

Syntax

initializer:
=assignment-expression
= {initializer-list,opt}
(
expression-list)

initializer-list:
expression
initializer-list
,expression
{initializer-list,opt}

There are two fundamental types of initializers:

The initializer invoked using the equal-sign syntax

The initializer invoked using function-style syntax

Which type of initializer works best in programs is largely a matter of style. Note that using the equal-sign syntax is semantically the same as using the function-style syntax; however, it is not the same as making an assignment.

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.

"Manteca",

"CA" );

The preceding code could also be written as follows, but the meaning of the initializations is not as clear:

int i( 7 );

Customer Cust = { "Taxpayer, Joe",

"14 Cherry Lane",

"Manteca",

"CA" };

The function-style initializer is more commonly used for objects like Cust that do not represent arithmetic types.

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” in Chapter 2, on topic .)