Export (0) Print
Expand All

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.

Grammar

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

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:

See Also

Declarators

Show:
© 2014 Microsoft