Information Technology Reference
In-Depth Information
Variable Initializers
Besides declaring a variable's name and type, a declaration can also initialize its memory to a
specific value.
A variable initializer consists of an equals sign followed by the initializing value, as
shown here:
Initializer
int var2 = 17;
Local variables without initializers have an undefined value, and cannot be used until they
have been assigned a value. Attempting to use an undefined variable causes the compiler to
produce an error message.
Figure 3-12 shows a number of local variable declarations on the left, and the resulting
stack configuration on the right. Some of the variables have initializers and others do not.
Figure 3-12. Variable initializers
Automatic Initialization
Some kinds of variables are automatically set to default values if they are declared without an
initializer, and others are not. Variables that are not automatically initialized to default values
contain undefined values until the program assigns them a value. Table 3-4 shows which types
of variables are automatically initialized and which are not.
Table 3-4. Types of Variables
Variable Type
Stored In
Auto-Initialized
Use
Local variables
Stack or stack and heap
No
Used for local computation inside
a function member
Members of a class
Class fields
Heap
Yes
Members of a struct
Struct fields
Stack or heap
Yes
Parameters
Stack
No
Used for passing values into and
out of a method
Array elements
Heap
Yes
Members of an array
Search WWH ::




Custom Search