Module 1 · Basics
1.1Variables and initialization
A variable is a named piece of memory with a type. Learn the basic types, the ways to give a variable its first value, why braces are the safe choice, and how const, constexpr and auto help.
On this page
- Key terms
- In 30 seconds
- Declaring a variable
- Three ways to initialize
- Braces refuse to lose data
- A variable needs a first value
- Values that don’t change: const and constexpr
- Letting the compiler pick the type: auto
- Scope: where a name can be used
- Shadowing
- Which one should I use?
- Under the hood
- Common pitfalls
- Empty parentheses declare a function
- Losing the fraction with =
- Changing the wrong variable
- Try it yourself
Key terms
- variable
- A named piece of memory that holds one value of a fixed type.
- type
- What kind of value a variable holds, like a whole number or text. It decides how many bytes the variable uses and what you can do with it.
int- A whole number, like
42or-7. double- A number with a fractional part, like
9.99. bool- A truth value:
trueorfalse. char- One character, like
'G', written in single quotes. std::string- A piece of text of any length, like
"GATTACA", written in double quotes. It comes from<string>. - initialize
- Give a variable its first value, in the same statement that declares it.
- brace initialization (
{}) - Initializing with braces, as in
int n{5};. It refuses conversions that would lose data. - narrowing conversion
- A conversion that can lose data, like
doubletoint(the fraction is dropped). - uninitialized variable
- A variable declared inside a function without a first value. It holds whatever bytes were already in its memory, and reading it is undefined behavior.
- undefined behavior
- Code the C++ rules give no meaning to. The compiler doesn't have to catch it, and the program might crash, print garbage or seem to work.
const- Marks a variable that can't be changed after it's initialized.
constexpr- Marks a constant whose value the compiler works out while compiling.
auto- Lets the compiler pick a variable's type from its initial value.
- scope
- The part of the code where a name can be used: from its declaration to the closing
}of its block. - block
- Code between
{and}. Variables declared inside it are local to it. - shadowing
- Declaring a variable in an inner block with the same name as one in an outer block. The inner one hides the outer one.
A program has to remember things while it runs: a count, a price, a DNA sequence, whether a file was found. You keep each one in a variable: a named piece of memory with a type. C++ checks every variable’s type when it compiles, so the choices you make here, about the type and the first value, decide which mistakes the compiler can catch for you.
In 30 seconds
- Declare a variable with its type, a name and a first value:
int count{0};. - Braces
{}are the safest way to initialize: they refuse conversions that lose data. - Always give a variable a first value. Reading one that has none is undefined behavior.
- Use
constfor values that never change,constexprfor values known when compiling, andautoto let the compiler pick the type.
Declaring a variable
A declaration names a type, then the variable, then its first value. The statement ends with ;.
#include <print>
#include <string>
int count = 3;
double price = 9.99;
bool found = true;
char base = 'G';
std::string sequence = "GATTACA";
std::println("{} {} {} {} {}", count, price, found, base, sequence);Output
3 9.99 true G GATTACA
These are the types you’ll use most at first:
intholds a whole number.doubleholds a number with a fractional part.boolholdstrueorfalse.charholds one character, in single quotes:'G'.std::stringholds text of any length, in double quotes:"GATTACA". It isn’t built into the language; it comes from the standard library, so you need#include <string>. Thestd::part says it belongs to the standard library.
Once declared, a variable can be given a new value with =. Its type never changes:
#include <print>
int count = 3;
count = 4;
count = count + 1;
std::println("{}", count);Output
5
count = count + 1 reads count, adds one, and stores the result back in count.
Three ways to initialize
C++ gives you three ways to write the first value. For a single number, all three do the same thing:
#include <print>
int a = 5; // copy initialization
int b{5}; // brace initialization
int c(5); // parentheses
int zero{}; // empty braces: zero
std::println("{} {} {} {}", a, b, c, zero);Output
5 5 5 0
Empty braces {} give a variable a zero value: 0 for numbers, false for a bool, an empty string for a std::string.
Braces refuse to lose data
The three forms differ when the value has to be converted. With =, a double quietly becomes an int, and the fraction is cut off:
#include <print>
double price = 9.99;
int whole = price; // the .99 is dropped, with no error
std::println("{}", whole);Output
9
That’s a narrowing conversion: the new type can’t hold every value of the old one, so data can be lost. Braces don’t allow it. The same line with braces doesn’t compile:
double price = 9.99;
int whole{price};The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:2:11: error: narrowing conversion of ‘price’ from ‘double’ to ‘int’ [-Werror=narrowing]
2 | int whole{price};
| ^~~~~
cc1plus: all warnings being treated as errorsIf you really want to drop the fraction, say so with static_cast<int>(price). Lesson 1.2, Integers and floating-point numbers, covers conversions like this.
Key ideaPrefer braces
int n{5}; works for every type and stops the compiler from silently changing your value. This site uses braces unless there’s a reason not to.
A variable needs a first value
Inside a function, you can declare a variable without a first value: int total;. Then it holds whatever bytes were already in its memory. Reading it before you assign to it is undefined behavior: the C++ rules don’t say what happens, so the program might print garbage, print 0 by luck, or do something stranger.
For simple cases like this one, GCC and Clang see the problem and warn. With warnings as errors, it doesn’t compile:
#include <print>
int total;
total = total + 5;
std::println("{}", total);The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:4:15: error: ‘total’ is used uninitialized [-Werror=uninitialized]
4 | total = total + 5;
| ~~~~~~^~~
main.cpp:3:5: note: ‘total’ declared here
3 | int total;
| ^~~~~
cc1plus: all warnings being treated as errorsThe fix is to start with a value: int total{0};. The compilers don’t catch every case, though, so make it a habit: give every variable a first value where you declare it.
Values that don’t change: const and constexpr
Put const before the type, and the variable can’t be changed after it’s initialized. It still gets its value when the program runs, so it can come from a calculation:
#include <print>
double length = 2.5;
const double area = length * length;
std::println("{}", area);Output
6.25
Changing a const variable is a compile error:
const int max_reads = 100;
max_reads = 200;The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:2:11: error: assignment of read-only variable ‘max_reads’
2 | max_reads = 200;
| ~~~~~~~~~~^~~~~constexpr goes further: the value must be known while the program is being compiled, so the compiler can work it out once and use the result directly. Use it for fixed settings like sizes and limits:
#include <print>
constexpr int bases_per_codon = 3;
constexpr int codons = 4;
constexpr int bases = bases_per_codon * codons;
static_assert(bases == 12);
std::println("{}", bases);Output
12
static_assert checks a condition while compiling and stops the build if it’s false. It only accepts values known at compile time, like a constexpr variable.
Modern C++const by default
Most variables get one value and keep it. Mark them const (or constexpr, when the value is fixed in the code), and the compiler tells you if you change one by accident. Readers of your code also know the value won’t change further down.
Letting the compiler pick the type: auto
With auto in place of a type, the compiler uses the type of the initial value. 3 is an int and 0.5 is a double, so:
#include <print>
#include <string>
auto reads = 3;
auto ratio = 0.5;
auto name = std::string{"chr1"};
std::println("{} {} {}", reads, ratio, name);Output
3 0.5 chr1
The type is still fixed: reads is an int for good. auto only saves you writing it. It needs an initial value to work from, so auto x; doesn’t compile. Use it when the type is obvious from the right-hand side, or long to write.
Scope: where a name can be used
A variable exists from its declaration to the } that closes its block, the code between { and }. That range is its scope. Outside it, the name doesn’t exist:
#include <print>
int total{0};
{
int bonus{5};
total = total + bonus;
}
std::println("{} {}", total, bonus);The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:8:30: error: ‘bonus’ was not declared in this scope
8 | std::println("{} {}", total, bonus);
| ^~~~~The fix is to declare bonus in the outer block, next to total, if you need it there.
Shadowing
A variable in an inner block can have the same name as one outside it. Inside the block, the inner one hides, or shadows, the outer one:
#include <print>
int count{10};
{
int count{3}; // a new variable that hides the outer count
std::println("inner: {}", count);
}
std::println("outer: {}", count);Output
inner: 3 outer: 10
This compiles without a warning, and it’s easy to change the wrong count by mistake. Give the inner variable its own name. (GCC and Clang warn about shadowing with -Wshadow, which isn’t part of -Wall -Wextra.)
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
constexpr | The value is fixed in the code: a size, a limit, a factor. | It’s computed while compiling and can be used in static_assert and other compile-time checks. | constexpr int max_len{150}; |
const | The value is computed when the program runs and doesn’t change afterwards. | The compiler stops you from changing it by accident. | const double area{length * length}; |
| Plain variable | The value has to change: a counter, a running total. | You can assign to it as often as you need. | int count{0}; |
auto | The type is obvious from the initial value, or long to write. | Less to read, and the type always matches the value. | auto name = std::string{"chr1"}; |
Rule of thumb: always initialize, prefer braces, and make a variable const unless it has to change.
Under the hood
A variable is a few bytes of memory with a name the compiler keeps track of. The type decides how many bytes: sizeof gives the size of a type or variable in bytes. These are the sizes on this site’s platform, 64-bit Linux:
#include <print>
int count{3};
double price{9.99};
bool found{true};
char base{'G'};
std::println("{} {} {} {}", sizeof(count), sizeof(price), sizeof(found),
sizeof(base));Output
4 8 1 1
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | Size |
|---|---|---|---|---|---|---|---|---|---|
int count | 34 bytes | 4 bytes | |||||||
double price | 9.998 bytes | 8 bytes | |||||||
bool found | true1 byte | 1 bytes | |||||||
char base | 'G'1 byte | 1 bytes | |||||||
count is an int and takes 4 bytes. price is a double and takes 8 bytes. found is a bool and takes 1 byte. base is a char and takes 1 byte. These sizes are for Linux on a 64-bit machine; lesson 1.2 shows which sizes can vary.
Names exist only for you and the compiler. The compiled program works with memory locations, and a constexpr value often doesn’t get memory at all: the compiler writes the number straight into the instructions that use it. const costs nothing at run time either; it’s a rule the compiler checks.
A std::string is different: its sizeof is the same however long the text is, because the characters usually live in a separate block of memory that the string manages for you. Lesson 2.1, Stack, heap and lifetime, shows where that block lives.
Undefined behaviorWhy uninitialized variables hold garbage
Declaring int total; inside a function reserves 4 bytes (on this platform) but doesn’t write to them. They still hold whatever an earlier part of the program left there. Setting them to zero for you would cost time, so C++ doesn’t, unless you ask with {}.
Common pitfalls
Empty parentheses declare a function
int c(5); makes an int, so you’d expect int count(); to make an int with value zero. It doesn’t: C++ reads it as a declaration of a function named count that returns an int. GCC and Clang warn, so with warnings as errors it doesn’t compile:
#include <print>
int count();
std::println("{}", count + 1);The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:3:10: error: empty parentheses were disambiguated as a function declaration [-Werror=vexing-parse]
3 | int count();
| ^~
main.cpp:3:10: note: remove parentheses to default-initialize a variable
3 | int count();
| ^~
| --
main.cpp:3:10: note: or replace parentheses with braces to value-initialize a variable
compilation terminated due to -fmax-errors=1.Use empty braces instead: int count{}; is an int with value 0.
Losing the fraction with =
int whole = price; drops the fraction without a word, as you saw above. If you write braces out of habit, the compiler catches it for you. If you mean it, write static_cast<int>(price) so the next reader knows it’s on purpose.
Changing the wrong variable
With shadowing, count = 0; inside a block changes the inner count and leaves the outer one alone. Avoid reusing a name from an outer block.
Try it yourself
Try it yourself
This program should print the cost of three items at 2.25 each, 6.75, but it prints 6. Switch every initialization to braces and let the compiler find the bug, then fix it. Make the price constexpr and the other two variables const.
#include <print>
int main() {
double price_per_item = 2.25;
int items = 3;
int total = price_per_item * items;
std::println("{}", total);
}Expected output
6.75
Show a hint
Change each = to braces and compile: the compiler points at the line that loses data. That variable has the wrong type.
Show a solution
#include <print>
int main() {
constexpr double price_per_item{2.25};
const int items{3};
const double total{price_per_item * items};
std::println("{}", total);
}With braces, int total{price_per_item * items} doesn't compile, because a double result can't fit in an int without losing the .75. Making total a double fixes it. The price is fixed in the code, so it can be constexpr, and items never changes, so it can be const.
Saved in this browser only.