|
|
|
|
|
|
|
Initializations in Declarations |
|
|
|
|
|
|
|
|
One of the most common things we do in programs is first declare a variable and then, in a separate statement, assign an initial value to the variable. Here's a typical example: |
|
|
|
|
|
|
|
|
C++ allows you to combine these two statements into one. The result is known as an initialization in a declaration. Here we initialize sum in its declaration: |
|
|
|
|
|
|
|
|
In a declaration, the expression that specifies the initial value is called an initializer. Above, the initializer is the constant 0. |
|
|
|
|
|
|
|
|
An automatic variable is initialized to the specified value each time control enters the block: |
|
|
|
|
|
|
|
|
void SomeFunc( int someParam )
{
int i = 0; // Initialized each time
int n = 2 * someParam + 3; // Initialized each time
.
.
.
} |
|
|
|
|
|
|
|
|
In contrast, initialization of a static variable (either a global variable or a local variable explicitly declared static) occurs once only, the first time control reaches its declaration. Furthermore, the initializer must be a constant expression (one with only constant values as operands). Here's an example: |
|
|
|
|
|
|
|
|
void AnotherFunc( int param )
{
static char ch = A; // Initialized once only
static int m = param + 1; // Illegal. Constant expression
// required
.
.
.
} |
|
|
|
|
|