Learn/C++/2. Values and variables
Lesson 2 of 15
Sign in

C++, lesson 2

Values and variables

A variable is a named piece of memory that holds a value. C++ is statically typed: each variable has a type that is fixed when you declare it, and the compiler checks every use.

Three ways to initialize

You will see all of these in real code:

Braces have one big advantage: they refuse narrowing conversions that would silently lose data.

Catching that mistake at compile time is worth the slightly unusual look, so this course uses braces for most declarations. int count{}; with empty braces starts at zero. A variable declared with no initializer at all (int n;) holds garbage until you assign it, so always initialize.

The common types

TypeHoldsExample
int

2 exercises to try what you just read.

Exercise 1

Player card

Press Ctrl Enter or Check to test your code.

Exercise 2

Light-year

Press Ctrl Enter or Check to test your code.

whole numbers, usually 32 bits (about ±2.1 billion)
-42
long longwhole numbers, at least 64 bits9'000'000'000LL
doublefloating-point numbers, about 15 significant digits2.5
chara single character'x'
booltrue or falsetrue
std::stringtext of any length"hello"

The ' in 9'000'000'000 is a digit separator; it only makes long numbers readable.

std::cout knows how to print all of these. A bool prints as 1 or 0 unless you first send std::boolalpha to the stream, after which it prints true or false.

auto

With auto, the compiler deduces the type from the initializer:

auto is handy when the type is long or obvious from the right-hand side. Note that auto s = "hi"; gives a C-style string pointer, not a std::string, which surprises people.

Constants

Mark values that should never change. const means "can't be modified after initialization"; constexpr additionally means "known at compile time", which lets the compiler use it in places like array sizes and lets it fold calculations away.

Prefer constexpr for fixed numbers, and const for values computed while the program runs.

Names

Names contain letters, digits and underscores and can't start with a digit. They are case sensitive. Choose names that explain the value: seconds_left beats s. Common C++ styles are snake_case (used by the standard library) and camelCase; pick one and stay consistent.

Further reading

  • cppreference: Fundamental types
  • cppreference: List initialization
  • cppreference: auto placeholder
  • cppreference: constexpr specifier

The starter declares the stats of a game character. Print them in exactly this format, using the variables. Alive must print as true, so send std::boolalpha to std::cout first.

The program reads no input.

Light travels 299'792 kilometres per second. Declare constexpr constants for the speed of light (km/s, a long long), seconds per day (86'400) and days per year (365). Compute how far light travels in one day and in one 365-day year, and print exactly:

The numbers are too big for int, so use long long. The program reads no input.

#include <string>

int lives{3};                  // whole number
double price{4.99};            // number with a fractional part
char grade{'B'};               // one character, single quotes
bool game_over{false};         // true or false
std::string name{"Ada"};       // text, double quotes; needs <string>
int a = 5;      // copy initialization, the classic form
int b(5);       // direct initialization
int c{5};       // brace (list) initialization, the modern default
int x = 3.9;    // compiles, x is 3 (the fraction is thrown away)
int y{3.9};     // compile error: narrowing from double to int
auto count = 12;        // int
auto ratio = 0.75;      // double
auto label = std::string{"total"};
constexpr int max_players{4};
const std::string greeting{"Welcome"};
// max_players = 5;   // error: assignment of read-only variable
Name: Ada
Level: 7
Health: 82.5
Grade: A
Alive: true
One light-day: 25902028800 km
One light-year: 9454240512000 km