Skip to content

Names and Initialized Values

The Course
•
35 min study

A program that prints 25 in three places has a problem as soon as the session becomes 30 minutes: you must find and change every copy, and missing one makes the output disagree with itself. A variable solves this. It gives a stored value a name, so you write the number once and refer to it everywhere else.

In C++ every variable also has a type, fixed when you declare it. int minutes = 25; stores a whole number. double hours = 0.5; stores a number with a fractional part. bool done = false; stores true or false. The type tells the compiler how much storage to set aside and which operations make sense, and the compiler rejects code that uses a value in a way its type does not allow.

Predict and run

Two variables change in the middle of this program and one cannot. Predict both output lines.

Predict before running C++
#include <iostream>

int main() {
    const int goal = 60;
    int minutes = 25;
    bool done = false;
    std::cout << minutes << " of " << goal << "\n";
    minutes = 30;
    done = true;
    std::cout << minutes << " " << done << "\n";
    return 0;
}
Check your prediction
Text
25 of 60
30 1

Each name held one value at a time. The first output statement ran while minutes was still 25; the assignment minutes = 30; replaced that value before the second output. By default a bool prints as 0 or 1, not as a word.

Initialize before you read

Always give a variable a value when you declare it. C++ does not promise that a fresh local int starts at zero. Reading it before it has a value is undefined behavior: the language makes no promise at all about what happens. The program might print 0, print a leftover number, or behave differently with another compiler or optimization setting.

C++
int minutes;               // declared, but holds no value yet
std::cout << minutes;      // undefined behavior: never do this

With -Wall, as in the local build on Day 7, the compiler warns about code like this, and that build's -Werror stops it. The browser editor builds without those flags, so here the program runs and prints whatever was in memory. Do not rely on that warning in general; some cases are too complex for the compiler to notice. Initialize every variable and the problem cannot occur.

You can also initialize with braces, as in int minutes{25};. Braces add a useful check: they refuse to silently lose information. int minutes{2.5}; is a compile error because 2.5 does not fit in an int, while int minutes = 2.5; would quietly keep only 2 on compilers that do not warn.

The = in a statement means "store this value now." It does not mean "these are equal forever," and it is not an equality test. Watch what happens to a total that was calculated from two durations when one of them changes later:

A stored total does not update itself C++
#include <iostream>

int main() {
    int first = 20;
    int second = 15;
    int total = first + second;
    second = 40;
    std::cout << "total " << total << "\n";
    total = first + second;
    std::cout << "total " << total << "\n";
    return 0;
}
Text
total 35
total 60

total received a copy of the sum at the moment the line ran. Changing second afterward did not reach back and change total. To get the new total you must calculate it again. Keeping this in mind will save you from a whole class of stale-value bugs.

const marks values that must not change

A const variable must be initialized and can never be assigned again. Use it for values such as a daily goal that should stay fixed while the program runs.

Run this program. It wants to try a harder day by changing the goal, and the compiler refuses to build it.

Fix the const error C++
#include <iostream>

int main() {
    const int goal = 60;
    int done = 45;
    std::cout << "Left: " << goal - done << " minutes\n";
    // A harder day: aim for 90 instead.
    goal = 90;
    std::cout << "Left: " << goal - done << " minutes\n";
    return 0;
}
Shell
main.cpp:8:10: error: cannot assign to variable 'goal' with const-qualified type 'const int'

Line 8, column 10 is the = in goal = 90;. That error is a feature. It turns a rule that lived in your head ("the goal never changes") into a rule the compiler enforces. So don't fix it by deleting const: the daily goal really is fixed. The harder target is a different value, so give it its own name. Repair the program so it prints Left: 15 minutes and then Stretch left: 45 minutes.

Check your fix

Replace the assignment with a second constant, and use it in the last line:

C++
#include <iostream>

int main() {
    const int goal = 60;
    int done = 45;
    std::cout << "Left: " << goal - done << " minutes\n";
    // A harder day: aim for 90 instead.
    const int stretch = 90;
    std::cout << "Stretch left: " << stretch - done << " minutes\n";
    return 0;
}
Text
Left: 15 minutes
Stretch left: 45 minutes

Types have limits

An int holds whole numbers in a fixed range, and a bool can be printed as a word if you ask the stream for it.

Inspect bool and int C++
#include <iostream>
#include <limits>

int main() {
    bool done = false;
    std::cout << done << " " << std::boolalpha << done << "\n";
    std::cout << std::numeric_limits<int>::max() << "\n";
    return 0;
}
Text
0 false
2147483647

std::boolalpha switches the stream to print true and false from then on. The largest int on this platform is 2147483647. Adding 1 to that value is signed integer overflow, which is undefined behavior, not a wrap to a negative number you can count on. This course keeps its numbers small, and later lessons validate input ranges so totals stay far from the limit.

Practice

Exercise

Your turn

Declare const int goal = 60; and two durations, first at 20 and second at 15. Print:

  • Total: 35 minutes
  • Left: 25 minutes

Then add 10 minutes to second, recalculate, and print the two lines again so the output ends with Total: 45 minutes and Left: 15 minutes. Derive every number from the variables.

Your workspace C++
#include <iostream>

int main() {
    // Write your solution here.
    return 0;
}
Hint 1: the idea

A total stored once will not follow later changes. Recalculate it after second changes.

Hint 2: a first step

Write int total = first + second; and print it with the goal minus the total. Then use second = second + 10; and assign total again.

Show one solution
Run the solution C++
#include <iostream>

int main() {
    const int goal = 60;
    int first = 20;
    int second = 15;
    int total = first + second;
    std::cout << "Total: " << total << " minutes\n";
    std::cout << "Left: " << goal - total << " minutes\n";

    second = second + 10;
    total = first + second;
    std::cout << "Total: " << total << " minutes\n";
    std::cout << "Left: " << goal - total << " minutes\n";
    return 0;
}
Text
Total: 35 minutes
Left: 25 minutes
Total: 45 minutes
Left: 15 minutes

goal stays fixed because it is const, while second and total are ordinary variables that you deliberately update. If you remove the second total = first + second;, the third line still says 35: proof that assignment copies a value rather than linking names. Next you will store text in a variable and see how division behaves with whole numbers.

Was this article helpful?

Your response is saved on this device.