Initialization
A teammate adds up the day's temperatures, and the total comes out as a nonsense number on one machine and correct on another. The loop is fine. The bug is the line before it: the total was never given a starting value. In C, creating a variable and giving it a value are two separate ideas, and it is up to you to join them.
The rule
Give every variable its value the moment it is born.
Initialization means supplying the value in the same statement that creates the variable:
int reading_count = 0;
double total = 0.0;
const int max_readings = 96; /* a const gets its only chance here */
int hourly[24] = {0}; /* all 24 elements are 0 */
int first_hours[5] = {215, 218, 220}; /* the last two are 0 */
int alarms[24] = {[6] = 1}; /* element 6 is 1, the rest are 0 */What happens when you don't initialize depends on where the variable lives:
- Local variables (inside a function, not
static) start with an indeterminate value. Reading one before you assign it is undefined behaviour: there is no correct answer to what it holds, and the program may print anything or misbehave in stranger ways. - File-scope and
staticvariables are set to zero automatically if you give no initializer. - For arrays and structs, once you give some initial values, every element you left out becomes zero.
The last line above uses a designated initializer (C99 and later): [6] = 1 names the element to set.
Initialization is not the same as assignment. int total = 0; initializes; a later total = 0; assigns. The difference matters for const: a const variable cannot be assigned, so its initializer is the only chance to give it a value. It also matters for arrays: int hourly[24] = {0}; is fine, but a later hourly = {0}; is an error, because a whole array cannot be assigned.
The shortcut
Put the equals sign on the same line as the type. If you cannot choose a sensible value yet, that is often a sign you are declaring the variable too early; move the line to where the value is known. And build with -Wall, which warns about many uses of uninitialized variables.
The bug
double total;inside the function, thentotal += hourly[h];24 times.
Drills
Answer fast — trust the rule.
What does int hourly[4] = {7}; contain?
Inside main: int count; printf("%d\n", count); What does it print?
A function contains static int boots;. What is its value on the very first call?
What does int alarms[24] = {[6] = 3}; do?
Why must max_readings get its value in const int max_readings = 96;?
Remember
- Give every variable its value the moment it is born.
- Shortcut: type and
=on the same line; build with-Wall. - Trap: locals start indeterminate and reading them is undefined behaviour; only
staticand file-scope variables start at zero.
