When we define a variable without an initializer, the system sometimes initializes the variable for us. What value, if any, is supplied depends on the type of the variable and may depend on where it is defined.
Initialization of Variables of Built-in Type
Whether a variable of built-in type is automatically initialized depends on where it is defined. Variables defined outside any function body are initialized to zero.
EXERCISES SECTION 2.3.3
Exercise 2.15: What, if any, are the differences between the following definitions:
- int month = 9, day = 7;
- int month = 09, day = 07;
If either definition contains an error, how might you correct the problem
Exercise 2.16: Assuming calc is a function that returns a double, which, if any, of the following are illegal definitions Correct any that are identified as illegal.
(a) int car = 1024, auto = 2048;
(b) int ival = ival;
(c) std::cin >> int input_value;
(d) double salary = wage = 9999.99;
(e) double calc = calc();
Variables of built-in type defined inside the body of a function are uninitialized. Using an uninitialized variable for anything other than as the left-hand operand of an assignment is undefined. Bugs due to uninitialized variables can be hard to find. As we cautioned on page 42, you should never rely on undefined behavior.
We recommend that every object of built-in type be initialized. It is not always necessary to initialize such variables, but it is easier and safer to do so until you can be certain it is safe to omit an initializer.
CAUTION: UNINITIALIZED VARIABLES CAUSE RUN-TIME PROBLEMS
Using an uninitialized object is a common programerror, and one that is often difficult to uncover. The compiler is not required to detect a use of an uninitialized variable, although many will warn about at least some uses of uninitialized variables. However, no compiler can detect all uses of uninitialized variables.
Sometimes, we’re lucky and using an uninitialized variable results in an immediate crash at run time. Once we track down the location of the crash, it is usually pretty easy to see that the variable was not properly initialized.
Other times, the program completes but produces erroneous results. Even worse, the results can appear correct when we run our program on one machine but fail on another. Adding code to the program in an unrelated location can cause what we thought was a correct program to suddenly start to produce incorrect results.
The problemis that uninitialized variables actually do have a value. The compiler puts the variable somewhere in memory and treats whatever bit pattern was in that memory as the variable’s initial state. When interpreted as an integral value, any bit pattern is a legitimate value—although the value is unlikely to be one that the programmer intended. Because the value is legal, using it is unlikely to lead to a crash. What it is likely to do is lead to incorrect execution and/or incorrect calculation.