Initialization and Assignment

When you give a variable a value as you create it, it's called initialization. Later, you can store a different value in it, and that's called assignment. To assign a value, write the name of the variable, = and the new value, but without the data type, because the variable already exists:

int score = 0;
std::cout << "Score: " << score << "\n";
score = 50;
std::cout << "Score: " << score << "\n";

This prints:

Score: 0
Score: 50

A program runs its statements one after another, from top to bottom. When the first print runs, score holds 0. The next line replaces it with 50, and the old value is gone. So the second print shows the new value.

A common mistake is to write the data type again when you assign a value: int score = 50;. That would create a second variable with the same name, and C++ doesn't allow it. The program doesn't compile, and the compiler reports redefinition of 'score': you're defining the name score a second time.

You can also store the value of another variable. A copy of the value is stored, so when you later change one of the variables, the other one stays the same:

int record = 50;
int score = record;
record = 80;
std::cout << score << " and " << record << "\n";

This prints:

50 and 80

You can also create a variable without a value and assign one later:

int score;
score = 50;

But until you store something in it, the variable has no defined value. It holds whatever happened to be left in its place in memory, and C++ doesn't stop you:

int score;
std::cout << "Score: " << score << "\n";

On this site, this program usually prints Score: 0, but on another computer it could print Score: 76646343, and something else the next time. So don't rely on zero, and give your variables a value when you create them: int score = 0;.

Instructions

temperature doesn't have a value yet, so the program prints a number that nobody stored in it. Initialize it: give it the value 12 when you create it. Then the program prints Morning: 12 degrees.

In the afternoon, it got warmer. Below the print, assign the new value 18 to temperature.

Below it, print the new value the same way, but with Afternoon instead of Morning. The program should print:

Morning: 12 degrees
Afternoon: 18 degrees

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

3/11

Next