CodeRigor

LESSON

Name values with variables

Store whole numbers, decimals and text in typed variables, calculate with them, update them and build lines of output from text and values.

The programs in the last lesson could only print text that you had typed in advance. To calculate anything, a program has to remember things: a price, a count, a name. This lesson shows how.

A variable is a named box for a value

A value is a piece of data, such as the number 4 or the text "notebook". A variable is a named place in the computer's memory that holds one value, so that later statements can use the value by name.

You create a variable by writing three things: what kind of value it holds, its name, and its first value.

C++
#include <iostream>

int main() {
    int price = 4;
    std::cout << price << '\n';
}

This prints 4. Line 4 creates a variable named price that holds whole numbers, and puts 4 in it. Programmers say that line defines the variable.

Line 5 sends two things to the screen, one after the other: the value of price, then a new line. Notice that price has no quotation marks. std::cout << "price" would show the word price; std::cout << price shows the value in the box.

The new line is written '\n' here, with single quotation marks. Single quotes hold exactly one character, and '\n' is the new-line character on its own. Use it when a line of output ends with a value and not with text.

Three kinds of value

Every value has a type, which says what kind of data it is. In C++ you state the type when you define a variable, and the variable keeps that type for as long as it exists. You need three types for now:

Kind of value Type to write Examples
whole number (integer) int 3, 0, -12
number with a decimal point double 2.5, 0.1, 3.0
text (string) std::string "notebook", "3"

The quotation marks matter: 3 is a number you can do arithmetic with, and "3" is a piece of text that happens to contain a digit.

To use std::string, add the line #include <string> at the top of the program, next to #include <iostream>.

C++
#include <iostream>
#include <string>

int main() {
    std::string item = "notebook";
    double price = 2.5;
    int quantity = 3;
    std::cout << item << '\n';
    std::cout << price << '\n';
    std::cout << quantity << '\n';
}

This prints notebook, 2.5 and 3, one per line.

Always give a variable a first value on the line that defines it. C++ allows int total; with no value, but then the box holds whatever happened to be in that piece of memory, and a program that uses it has no predictable result.

Arithmetic

C++ calculates with the symbols below, which are called operators.

C++
#include <iostream>

int main() {
    std::cout << 7 + 2 << '\n';    // add
    std::cout << 7 - 2 << '\n';    // subtract
    std::cout << 7 * 2 << '\n';    // multiply
    std::cout << 7 / 2 << '\n';    // divide two whole numbers
    std::cout << 7 % 2 << '\n';    // the remainder of that division
    std::cout << 7.0 / 2 << '\n';  // divide when one side is a double
}

This prints 9, 5, 14, 3, 1 and 3.5, one per line.

Two details are worth remembering:

  • Dividing one int by another gives an int, and the part after the decimal point is thrown away. 7 / 2 is 3, not 3.5. If either side is a double, the answer is a double: 7.0 / 2 is 3.5.
  • Multiplication and division happen before addition and subtraction, as in maths. 2 + 3 * 4 is 14. Use round brackets to choose a different order: (2 + 3) * 4 is 20.

Assignment works out the right-hand side first

After a variable exists, you can put a new value in it with an assignment statement: the name, an equals sign, then the new value. There is no type in front this time, because the variable already exists.

In C++, = does not mean "is equal to" as it does in maths. It means "work out the right-hand side, then store the result in the variable on the left". Read quantity = 5 as "quantity becomes 5".

C++
#include <iostream>

int main() {
    int price = 4;
    int quantity = 3;
    int total = price * quantity;
    std::cout << total << '\n';
    quantity = 5;
    std::cout << total << '\n';
}

This prints 12 and then 12 again. Step through the diagram to see why the second line of output is not 20.

What each variable holds, line by line
start / 6 ⇄ code
total was given the value 12 when line 6 ran. Changing quantity later does not go back and recalculate it.
What each variable holds, line by line
total was given the value 12 when line 6 ran. Changing quantity later does not go back and recalculate it.

A variable does not remember how its value was calculated. It holds the finished result.

How one assignment statement runs
start / 3
The right-hand side is finished before the variable on the left is touched. That is why count = count + 1; makes sense: the old value is used first, then the new value replaces it.
How one assignment statement runs
The right-hand side is finished before the variable on the left is touched. That is why count = count + 1; makes sense: the old value is used first, then the new value replaces it.
C++
#include <iostream>

int main() {
    int count = 7;
    count = count + 1;
    std::cout << count << '\n';
}

This prints 8. As a maths equation, count = count + 1 would be nonsense. As an instruction it is ordinary: "work out count + 1, then store the answer in count".

Choosing names

A variable name may contain letters, digits and underscores (_). It may not start with a digit, it may not contain spaces, and it may not be a word that C++ uses itself, such as int or double. Capital letters count, so total and Total are two different names.

This unit writes names in lower case with underscores between the words: unit_price, first_name. Choose names that say what the value means. price is better than p, and far better than x.

Putting values into printed text

Repeat << to send text and values one after another. Nothing is added between them, so any spaces you want must be inside your strings.

C++
#include <iostream>
#include <string>

int main() {
    std::string item = "notebook";
    int quantity = 3;
    double price = 2.5;
    std::cout << "Item: " << item << '\n';
    std::cout << quantity << " of them\n";
    std::cout << "Total: " << price * quantity << " pounds\n";
}

This prints:

Text
Item: notebook
3 of them
Total: 7.5 pounds

Look at the space after the colon in "Item: " and the one before of. Without them the output would read Item:notebook and 3of them.

The last statement sends a calculation. The computer works out price * quantity first and sends the answer. Because price is a double, the answer is the double 7.5.

std::cout shows a double in the shortest sensible way: 7.5 and not 7.50, and a double holding 6.0 is shown as 6.

Between two std::string values, + joins them end to end:

C++
#include <iostream>
#include <string>

int main() {
    std::string first = "Ada";
    std::string last = "Lovelace";
    std::string full = first + " " + last;
    std::cout << full << '\n';
}

This prints Ada Lovelace. Use + only to join strings to strings. To put a number next to text in the output, send them one after the other with <<, as above.

A newer way to print

Recent versions of C++ add a second way to print, std::println, which you may meet in newer programs. You write the whole line as one string with {} wherever a value belongs, and it ends the line for you:

C++
#include <print>

int main() {
    int quantity = 3;
    double total = 7.5;
    std::println("{} notebooks cost {} pounds", quantity, total);
}

This prints 3 notebooks cost 7.5 pounds. std::println needs #include <print> and a recent compiler (on your own computer, GCC and Clang need -std=c++23 added to the compile command).

This unit uses std::cout, because it is what you will read in almost every existing C++ program, and because the exercises check only what your program sends to std::cout.

Two errors you will meet

A misspelt variable name. The compiler only knows the names you have defined.

C++
#include <iostream>

int main() {
    int total = 12;
    std::cout << total << '\n';
    std::cout << totl * 2 << '\n';
}
Text
main.cpp: In function 'int main()':
main.cpp:6:18: error: 'totl' was not declared in this scope; did you mean 'total'?
    6 |     std::cout << totl * 2 << '\n';
      |                  ^~~~
      |                  total

Find the line with error. "Was not declared in this scope" is the compiler's way of saying "I have not been told about this name here". The position is line 6, character 18, the ^~~~ marks sit under the unknown name, and this time the suggestion is right. The fix is to spell the name the way it was defined.

A value of the wrong type. A variable can only hold values of its own type.

C++
#include <iostream>

int main() {
    int count = "three";
    std::cout << count << '\n';
}
Text
main.cpp: In function 'int main()':
main.cpp:4:17: error: invalid conversion from 'const char*' to 'int' [-fpermissive]
    4 |     int count = "three";
      |                 ^~~~~~~
      |                 |
      |                 const char*

A "conversion" is a change from one type to another, and const char* is the compiler's own name for text written in quotation marks. So the message says: line 4 tries to turn a piece of text into an int, and that is not allowed. The ^~~~~~~ marks sit under the text. Either write a number, int count = 3;, or make the variable a string, std::string count = "three";. You can ignore the part in square brackets at the end of the first line.

What you can do now

You can define variables of three types, calculate with them, update a variable, and build lines of output from text and values. In the exercises you will predict what assignments and calculations print, then write a program that works out and prints a receipt.

Next: read what the user types, so that the values can come from the person running the program.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Starts at 'Variables and basic data types' (13:30) and runs to 24:14: defining int, double and string variables and printing them. The chapter 'Arithmetic operators' (37:39 to 43:18) covers the calculations in this lesson; the chapters in between can wait.

Starts at 'Variables' (19:52). The chapters 'Naming Conventions', 'Mathematical Expressions', 'Order of Operators' and 'Writing Output to the Console' follow, ending at 49:06. Together they cover this whole lesson at a slower pace.