C++ Module 2 – Types, values and expressions
C++ auto, decltype and type aliases
What auto deduces from references and const, how decltype names the type of an expression, and how using makes aliases: every rule proved by the compiler.
What you will learn
- Use auto where the type is obvious or cannot be spelled
- Predict what auto deduces from references and const
- Predict what decltype gives for a name, a name in parentheses and a call
- Detect the copies and proxies that auto makes where a reference or a value was meant
- Write readable aliases with using
Before you start
What you’ll learn · Before you start
What you will learn
- Use auto where the type is obvious or cannot be spelled
- Predict what auto deduces from references and const
- Predict what decltype gives for a name, a name in parentheses and a call
- Detect the copies and proxies that auto makes where a reference or a value was meant
- Write readable aliases with using
Before you start
On this page
for (auto p : prices) p *= 2; compiles and runs, and the prices 40, 25 and 60 stay exactly as they were: each p
was a copy. auto in a declaration tells the compiler to take the variable’s type from its initializer:
auto n = 7; makes n an int. It removes long type names, it is the only way to declare a variable whose type
cannot be written, such as a lambda, and it never leaves a variable uninitialised. But it
type deduction: The compiler working out a type from an initializer or an argument instead of reading it from the declaration, as it does for auto, decltype(auto) and the parameters of function templates. the type of the value, so it drops references and the const of the
initializer itself: auto x = some_reference; makes a copy. Write auto& or const auto& when you want a
reference.
decltype(expr) gives the type of an expression exactly as declared, references and const included.
using Name = Type; creates an alias, a second name for an existing type, and also works for templates. Each
deduction below is shown on Apple clang 21 and GCC 16, by a static_assert or by what the program prints.
auto takes the type of the value
Each line below declares a variable with auto, and a static_assert beneath states its type; if any statement were
wrong, the file would not compile. std::is_same_v<A, B> is true exactly when A and B are the same type.
// What auto deduces, checked by the compiler:
// each static_assert stops the build if the type is not the one it names.
#include <print>
#include <string>
#include <type_traits>
#include <vector>
int main() {
int count = 7;
const int limit = 10;
int& ref = count;
const int& cref = limit;
const int* p = &limit;
int scores[3] = {90, 75, 60};
std::vector<std::string> names{"Asha", "Ravi"};
auto a = count; // int
auto b = limit; // int: the const of the variable itself is dropped
auto c = ref; // int: a copy, the reference is dropped
auto d = cref; // int: both dropped
auto e = p; // const int*: a pointer to const keeps that const
auto f = scores; // int*: an array decays to a pointer to its first element
auto g = "chai"; // const char*: a string literal is an array of const char
auto h = names[0]; // std::string: a copy of the element
auto i{5}; // int (since C++17)
auto j = {5}; // std::initializer_list<int>, not int
static_assert(std::is_same_v<decltype(a), int>);
static_assert(std::is_same_v<decltype(b), int>);
static_assert(std::is_same_v<decltype(c), int>);
static_assert(std::is_same_v<decltype(d), int>);
static_assert(std::is_same_v<decltype(e), const int*>);
static_assert(std::is_same_v<decltype(f), int*>);
static_assert(std::is_same_v<decltype(g), const char*>);
static_assert(std::is_same_v<decltype(h), std::string>);
static_assert(std::is_same_v<decltype(i), int>);
static_assert(std::is_same_v<decltype(j), std::initializer_list<int>>);
c = 100; // changes the copy only, not count
std::println("a={} b={} c={} d={} *e={} f[0]={}", a, b, c, d, *e, f[0]);
std::println("g={} h={} i={} j.size()={} count={}", g, h, i, j.size(), count);
} from session import run
run("""
clang++ --version | head -n 1
clang++ -std=c++23 -Wall -Wextra deduction.cpp -o deduction && ./deduction
g++-16 --version | head -n 1
g++-16 -std=c++23 -Wall -Wextra deduction.cpp -o deduction && ./deduction
""") Output
$ clang++ --version | head -n 1 Apple clang version 21.0.0 (clang-2100.3.34.2) $ clang++ -std=c++23 -Wall -Wextra deduction.cpp -o deduction && ./deduction a=7 b=10 c=100 d=10 *e=10 f[0]=90 g=chai h=Asha i=5 j.size()=1 count=7 $ g++-16 --version | head -n 1 g++-16 (Homebrew GCC 16.2.0) 16.2.0 $ g++-16 -std=c++23 -Wall -Wextra deduction.cpp -o deduction && ./deduction a=7 b=10 c=100 d=10 *e=10 f[0]=90 g=chai h=Asha i=5 j.size()=1 count=7
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 deduction_session.py
The file builds on both compilers, so all ten statements hold. The rules behind them:
- The reference is dropped.
canddcome from references, but they are newintvariables holding copies: afterc = 100;,countis still 7. - top-level const: A const that applies to an object itself, as in const int or int* const, rather than to what a pointer or a reference leads to. auto drops it, because the new variable is a separate object. is dropped.
bis a plainintalthoughlimitisconst int:constdescribes the variablelimit, andbis a different variable. Aconstthat belongs to the type pointed to is kept, soeisconst int*: it still may not changelimitthrough the pointer. - Arrays become pointers.
fisint*, a pointer toscores[0], andg, from a string literal, isconst char*. Neither copies the array. - Braces need care. Since C++17
auto i{5};is anint, butauto j = {5};is astd::initializer_list<int>, a list with one element, which is rarely what was meant.
The diagram follows one initializer, a const int&, down both paths: auto drops the reference and then the
const, while auto& keeps both.
What auto and auto& deduce from a const reference
Text description of the diagram
The diagram starts from one initializer, const int& cref = limit;, and follows two arrows.
- The arrow labelled auto goes down through two steps. First the reference is dropped, which leaves const int. Then the top-level const is dropped, which leaves int. So auto x = cref; makes x an int, a copy of the value.
- The arrow labelled auto& goes to auto& r = cref;. With the & written out, nothing is dropped: r is a const int&, a reference to the same object that still cannot be changed through r.
Step through six of the ten declarations, one at a time, and watch the type change at each stage, from the reference
that goes first to the array-to-pointer conversion: The implicit conversion of an array to a pointer to its first element, which happens in most uses of an array, such as auto f = scores;. The pointer no longer carries the array's length. that turns scores
into an int*:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- auto c = ref;. ref is an int& bound to count. The reference is dropped first, so c is a new int holding a copy of 7: after c = 100; the program still printed count=7.
- auto d = cref;. cref is a const int& bound to limit. Dropping the reference leaves const int, and that const belongs to d itself, so it goes too: d is a plain int that may change.
- auto e = p;. p is a const int*. Here the const belongs to the int that p points at, not to p, so it is not top-level and auto keeps it: e is a const int*, and *e printed 10.
- auto f = scores;. scores is an array of 3 ints. auto cannot copy an array, so the array becomes a pointer to its first element: f is an int*, and f[0] printed 90.
- auto g = "chai";. A string literal is an array of const char, 5 of them with the final zero. The array becomes a pointer, and the const of the characters stays: g is a const char*.
- auto j = {5};. With = and braces, auto deduces a std::initializer_list<int> before any of these rules apply: j is a list with 1 element, as j.size() printed. auto i{5}; without the = is an int.
Every type in the figure is one of the static_assert lines of deduction.cpp, so the compiler has already checked
each stage of it.
Key idea
auto makes a new variable from the value: the reference and the const of the initializer itself are dropped, a
const behind a pointer stays, an array becomes a pointer, and = {…} makes a std::initializer_list.
Checkpoint
Check: What auto drops from an initializer
auto& and const auto& refer to the original; auto&& binds to anything
When you want the original object rather than a copy, say so. The difference matters most in range-based for: A loop of the form for (declaration : range) that runs its body once for each element of an array, a container or another range, in order, with no index to manage. auto copies each element; auto& refers to it. More in “C++ loops: while, do-while, for and range-for”:
// auto makes a copy; auto& and const auto& refer to the original.
// The loop that doubles nothing is a classic bug.
#include <print>
#include <string>
#include <vector>
int main() {
std::vector<int> prices{40, 25, 60};
for (auto p : prices) p *= 2; // p is a copy of each element: the vector does not change
std::println("after auto: {}", prices);
for (auto& p : prices) p *= 2; // p refers to each element: the vector changes
std::println("after auto&: {}", prices);
const std::vector<std::string> cities{"Bengaluru", "Chennai", "Kolkata"};
std::size_t letters = 0;
for (const auto& city : cities) letters += city.size(); // reads each string without copying it
std::println("{} letters in {} names", letters, cities.size());
int x = 1;
auto&& r1 = x; // a forwarding reference: binds to x as int&
auto&& r2 = 42; // ... and to a temporary as int&&
r1 = 5;
std::println("x = {}, r2 = {}", x, r2);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra references.cpp -o references && ./references
g++-16 -std=c++23 -Wall -Wextra references.cpp -o references && ./references
""") Output
$ clang++ -std=c++23 -Wall -Wextra references.cpp -o references && ./references
references.cpp:10:15: warning: variable 'p' set but not used [-Wunused-but-set-variable]
10 | for (auto p : prices) p *= 2; // p is a copy of each element: the vector does not change
| ^
1 warning generated.
after auto: [40, 25, 60]
after auto&: [80, 50, 120]
23 letters in 3 names
x = 5, r2 = 42
$ g++-16 -std=c++23 -Wall -Wextra references.cpp -o references && ./references
references.cpp: In function 'int main()':
references.cpp:10:15: warning: variable 'p' set but not used [-Wunused-but-set-variable=]
10 | for (auto p : prices) p *= 2; // p is a copy of each element: the vector does not change
| ^
after auto: [40, 25, 60]
after auto&: [80, 50, 120]
23 letters in 3 names
x = 5, r2 = 42
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 references_session.py
The first loop doubled copies, so the vector did not change. Both compilers warn that p is set but never used, which
is the clue here; for a copy of a class type, such as a std::string, they stay silent, so the habit of writing
references in loops matters more than the warning. auto& refers to each element, so the second loop changed them.
const auto& reads each string without copying it, which is the usual way to loop over strings or other large
objects that you only read.
Step through both loops over prices, one pass at a time. A dashed arrow means p is a copy of the element, a solid
one that p is the element itself:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- auto, pass 1. for (auto p : prices) makes p a new int, a copy of prices[0]. p *= 2 turns the copy into 80, while prices[0] is still 40.
- auto, pass 2. Each pass copies again: p starts as 25 and becomes 50, and the copy is destroyed at the end of the pass. The vector never sees the change.
- auto, pass 3. The last copy becomes 120. The program printed after auto: [40, 25, 60], and both compilers warned that p is set but never used.
- auto&, pass 1. for (auto& p : prices) makes p refer to prices[0] itself, so p *= 2 doubles the element: 40 becomes 80 inside the vector.
- auto&, pass 2. On the next pass p refers to prices[1], and 25 becomes 50. No int is copied: p is only a second name for the element.
- auto&, pass 3. prices[2] becomes 120, and the program printed after auto&: [80, 50, 120]. Every change reached the vector, because p was each element in turn.
The first loop made three copies, changed them and threw them away; the second wrote all three changes into the
vector, because p was each element in turn.
auto&& is a forwarding reference: A reference written auto&&, or T&& in a template whose T is deduced, that binds to anything: it becomes an lvalue reference for a named variable and an rvalue reference for a temporary.: it binds to anything, as int& to a named
variable (r1 changed x) and as int&& to a temporary such as 42. You will meet it in generic code; in everyday
loops auto& and const auto& say more clearly what you mean.
A loop that changes copies
for (auto p : prices) p *= 2; doubles three copies and leaves prices at [40, 25, 60]. Write
for (auto& p : prices) to change the elements, and for (const auto& city : cities) to read large elements
without copying them.
Checkpoint
Check: auto&, const auto& and auto&&
decltype keeps what auto drops
decltype(e) gives the type of an expression without evaluating it, and it keeps what auto drops:
// decltype(name) is the declared type of a variable;
// decltype((name)), with extra parentheses, is a reference.
#include <print>
#include <type_traits>
#include <vector>
int main() {
int x = 0;
const int c = 1;
std::vector<int> v{1, 2, 3};
static_assert(std::is_same_v<decltype(x), int>);
// (x) is an expression that names an object
static_assert(std::is_same_v<decltype((x)), int&>);
// decltype keeps the const that auto drops
static_assert(std::is_same_v<decltype(c), const int>);
static_assert(std::is_same_v<decltype(v[0]), int&>); // what operator[] returns
static_assert(std::is_same_v<decltype(x + 1), int>); // a computed value, not a reference
auto copy = v[0]; // int
decltype(auto) same = v[0]; // int&: the exact type of the initializer
same = 10;
copy = 20;
std::println("v = {}, copy = {}", v, copy);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra decltype_rules.cpp -o decltype_rules && ./decltype_rules
g++-16 -std=c++23 -Wall -Wextra decltype_rules.cpp -o decltype_rules && ./decltype_rules
""") Output
$ clang++ -std=c++23 -Wall -Wextra decltype_rules.cpp -o decltype_rules && ./decltype_rules v = [10, 2, 3], copy = 20 $ g++-16 -std=c++23 -Wall -Wextra decltype_rules.cpp -o decltype_rules && ./decltype_rules v = [10, 2, 3], copy = 20
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 decltype_session.py
decltype(c) is const int, the declared type of c. decltype(v[0]) is int&, because operator[] returns a
reference. The odd rule is the one with extra parentheses: decltype(x) names the variable and gives its declared
type, int, while decltype((x)) is an expression that refers to an object, an lvalue: An expression that refers to an object with an identity, such as a named variable, (x) or v[0]. decltype gives a reference type, such as int&, for an lvalue that is not a plain name., and
so gives int&.
decltype(auto) deduces like decltype instead of like auto: same became an int&, so same = 10; changed
v[0], while copy = 20; changed only the copy. It is mostly used for function return types that must keep a
reference.
Put side by side, the two forms agree on two of five initializers and differ on three. Every cell of this table is a
static_assert in the program under it:
Initializer e |
auto a = e; gives |
decltype(e) gives |
|---|---|---|
x, an int variable |
int |
int |
(x), the same name in parentheses |
int |
int& |
c, a const int variable |
int |
const int |
v[0], an element of a std::vector<int> |
int, a copy |
int& |
x + 1, a computed value |
int |
int |
// The same five initializers through auto and through decltype.
// Each static_assert is one cell of the table: the build stops if any cell is wrong.
#include <print>
#include <type_traits>
#include <vector>
int main() {
int x = 0;
const int c = 1;
std::vector<int> v{7, 8, 9};
// auto deduces the type of the value: a copy, never a reference, never const.
auto a1 = x;
auto a2 = (x);
auto a3 = c;
auto a4 = v[0];
auto a5 = x + 1;
static_assert(std::is_same_v<decltype(a1), int>);
static_assert(std::is_same_v<decltype(a2), int>);
static_assert(std::is_same_v<decltype(a3), int>);
static_assert(std::is_same_v<decltype(a4), int>);
static_assert(std::is_same_v<decltype(a5), int>);
// decltype keeps what auto drops.
static_assert(std::is_same_v<decltype(x), int>);
static_assert(std::is_same_v<decltype((x)), int&>);
static_assert(std::is_same_v<decltype(c), const int>);
static_assert(std::is_same_v<decltype(v[0]), int&>);
static_assert(std::is_same_v<decltype(x + 1), int>);
a4 = 70; // a copy: v[0] is still 7
std::println("a1={} a2={} a3={} a4={} a5={} v[0]={}", a1, a2, a3, a4, a5, v[0]);
} Output
a1=0 a2=0 a3=1 a4=70 a5=1 v[0]=7
Recorded with Apple clang version 21.0.0 (clang-2100.3.34.2) on macOS 26 arm64. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined auto_vs_decltype.cpp -o auto_vs_decltype && ./auto_vs_decltype
Both compilers built it with every warning turned into an error, and a4 = 70 left v[0] at 7: the auto column
copies, and the decltype column keeps references and const.
Key idea
decltype of a plain name gives the type the name was declared with; any other expression that refers to an
object, such as (x) or v[0], gives a reference.
Checkpoint
Check: decltype and decltype(auto)
auto keeps the proxy that std::vector<bool> hands out
auto takes whatever type the initializer has, even when that is not the type you had in mind.
std::vector<bool> stores its values as single bits, so flags[i] cannot return a bool&; it returns a small
proxy object: An object returned in place of a reference, standing for an element that cannot be referred to directly, as std::vector<bool>::reference stands for one bit. It points into its container and is valid only while the container lives., std::vector<bool>::reference, that points into the vector. With
auto, the variable is that proxy:
// std::vector<bool> packs its values into bits, so v[i] returns a small proxy object, not a bool&.
// auto then deduces the proxy type, which still points into the vector.
#include <print>
#include <type_traits>
#include <vector>
std::vector<bool> make_flags() { return std::vector<bool>(1000, false); }
int main() {
std::vector<bool> flags(1000, false);
auto first = flags[0]; // not a bool: a std::vector<bool>::reference
static_assert(!std::is_same_v<decltype(first), bool>);
first = true; // writes into the vector
std::println("flags[0] is now {}", static_cast<bool>(flags[0]));
bool copy = flags[1]; // naming the type converts the proxy to a plain bool
copy = true;
std::println("flags[1] is still {}, copy is {}", static_cast<bool>(flags[1]), copy);
auto dangling = make_flags()[0]; // a proxy into a temporary, destroyed at the end of this line
std::println("reading it: {}", static_cast<bool>(dangling)); // reads freed memory
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined vector_bool.cpp -o vector_bool && ./vector_bool
g++-16 -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined vector_bool.cpp -o vector_bool && ./vector_bool
""") Output
$ clang++ -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined vector_bool.cpp -o vector_bool && ./vector_bool
flags[0] is now true
flags[1] is still false, copy is true
=================================================================
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 8 at 0x… thread T0
#1 in main vector_bool.cpp:22
0x… is located 0 bytes inside of 128-byte region [0x…,0x…)
freed by thread T0 here:
#7 in main vector_bool.cpp:21
previously allocated by thread T0 here:
#9 in make_flags() vector_bool.cpp:7
#10 in main vector_bool.cpp:21
SUMMARY: AddressSanitizer: heap-use-after-free
[56 more lines of the report left out]
[exit status 134]
$ g++-16 -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined vector_bool.cpp -o vector_bool && ./vector_bool
flags[0] is now true
flags[1] is still false, copy is true
=================================================================
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 8 at 0x… thread T0
#1 in main vector_bool.cpp:22
0x… is located 0 bytes inside of 128-byte region [0x…,0x…)
freed by thread T0 here:
#5 in main vector_bool.cpp:21
previously allocated by thread T0 here:
#5 in make_flags() vector_bool.cpp:7
#6 in main vector_bool.cpp:21
SUMMARY: AddressSanitizer: heap-use-after-free
[50 more lines of the report left out]
[exit status 134]
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 vector_bool_session.py
first = true; wrote into the vector, while the bool copy did not. (sanitizer: A compiler option, such as -fsanitize=address or -fsanitize=undefined, that builds extra checks into a program, so that memory errors and undefined behaviour are reported, with their source line, while it runs. More in “Finding memory bugs with AddressSanitizer and UBSan”
reports run to dozens of lines, so the sessions keep the lines that name the error and this lesson’s own files, and
write the memory addresses, which change on every run, as 0x….) The last two lines are the dangerous case:
make_flags()[0] is a proxy into a temporary vector that is destroyed at the end of the line, so reading it reads
freed memory. AddressSanitizer stops the program and names both lines, line 21 where the memory was allocated and
freed and line 22 where it was read; without the sanitizer the program might print a plausible value. Write the type
(bool b = flags[0];) when you want the value.
Step through the program and follow what each variable points into, up to the read that AddressSanitizer stops:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- A proxy, not a bool. std::vector<bool> keeps each value as one bit, so flags[0] cannot return a bool&. It returns a std::vector<bool>::reference that points at bit 0, and auto keeps that proxy: the static_assert proves first is not a bool.
- Writing through it. first = true; writes through the proxy into the vector, and the program printed flags[0] is now true.
- Naming the type. bool copy = flags[1]; converts the proxy to a plain bool once. copy = true; changes only copy, and the program printed flags[1] is still false, copy is true.
- A proxy into a temporary. make_flags() returns a temporary vector whose bits fill a 128-byte block, allocated on line 7, and [0] hands out a proxy into it. auto dangling keeps the proxy.
- The end of line 21. The temporary vector is destroyed at the end of the full expression on line 21, and its 128 bytes are freed. dangling still points into them.
- Line 22 reads it. static_cast<bool>(dangling) reads the freed memory. AddressSanitizer stopped both builds with a heap-use-after-free report that names lines 21 and 22, and the run ended with exit status 134.
Neither compiler warned about line 21, and nothing on that line looks wrong: the type that auto deduced is the
whole problem.
Checkpoint
Check: The proxy of std::vector<bool>
auto keeps the exact type of a literal or a size
Number types are the other surprise. A literal or an expression has a type of its own, and auto keeps it:
// auto takes the type of a literal or an expression exactly as it is,
// which is not always the type you wanted.
#include <cstddef>
#include <print>
#include <type_traits>
#include <vector>
int main() {
auto small = 3'000; // int
auto big = 3'000'000'000; // too big for int: long here, long long on Windows
auto size = std::vector<int>(5).size(); // std::size_t, an unsigned type
static_assert(std::is_same_v<decltype(small), int>);
static_assert(std::is_same_v<decltype(big), long>);
static_assert(std::is_same_v<decltype(size), std::size_t>);
std::vector<int> v{3, 1, 4};
for (auto i = 0; i < v.size(); ++i) { // int i against an unsigned size: a mixed comparison
std::print("{} ", v[i]);
}
std::println("| sizes in bytes: {} {} {}", sizeof small, sizeof big, sizeof size);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra integer_auto.cpp -o integer_auto && ./integer_auto
g++-16 -std=c++23 -Wall -Wextra integer_auto.cpp -o integer_auto && ./integer_auto
""") Output
$ clang++ -std=c++23 -Wall -Wextra integer_auto.cpp -o integer_auto && ./integer_auto
integer_auto.cpp:17:24: warning: comparison of integers of different signs: 'int' and 'size_type' (aka 'unsigned long') [-Wsign-compare]
17 | for (auto i = 0; i < v.size(); ++i) { // int i against an unsigned size: a mixed comparison
| ~ ^ ~~~~~~~~
1 warning generated.
3 1 4 | sizes in bytes: 4 8 8
$ g++-16 -std=c++23 -Wall -Wextra integer_auto.cpp -o integer_auto && ./integer_auto
integer_auto.cpp: In function 'int main()':
integer_auto.cpp:17:24: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
17 | for (auto i = 0; i < v.size(); ++i) { // int i against an unsigned size: a mixed comparison
| ~~^~~~~~~~~~
3 1 4 | sizes in bytes: 4 8 8
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 integer_auto_session.py
3'000'000'000 does not fit in a 32-bit int, so the literal is a long, 8 bytes on 64-bit macOS and Linux. On
Windows long has 4 bytes, so the same literal is a long long there. size() returns std::size_t, an unsigned
type, while auto i = 0 makes an int, and the comparison of the two in the loop condition gets a
-Wsign-compare warning from both compilers. In such a comparison the int is converted to the unsigned type, so a
negative value would compare as a huge number. Declare the loop variable as std::size_t, or loop over the elements
with for (int x : v).
The three variables of the program, with the sizes it printed on this 64-bit Mac, 4 8 8:
| Initializer | auto deduces |
Bytes here |
|---|---|---|
3'000 |
int |
4 |
3'000'000'000 |
long (long long on Windows) |
8 |
std::vector<int>(5).size() |
std::size_t, unsigned |
8 |
None of the three types is written in the program, and only the first is an int: read the type off the
initializer before you trust auto with a number.
Checkpoint
Check: The types of literals and sizes
using gives a type a second name, not a new type
using Name = Type; gives an existing type a second name, a type alias: A second name for an existing type, made with using Name = Type; or typedef. It makes no new type, so values of the alias and of the original type mix freely.. It reads left to
right, like an assignment, and unlike the older typedef it can also be a
alias template: A type alias with template parameters, such as template <typename T> using Grid = std::vector<std::vector<T>>;, which typedef cannot write.:
// using gives an existing type a second name. It does not create a new type,
// so mixing up two aliases of the same type still compiles.
#include <cstdint>
#include <map>
#include <print>
#include <string>
#include <type_traits>
#include <vector>
using Score = std::int32_t;
// much shorter to write than the type it names
using Marks = std::map<std::string, std::vector<Score>>;
template <typename T>
// an alias template: typedef cannot do this
using Grid = std::vector<std::vector<T>>;
typedef std::int32_t OldScore; // the older way to write the same alias
using Metres = double;
using Seconds = double;
int main() {
static_assert(std::is_same_v<Score, std::int32_t>);
static_assert(std::is_same_v<Score, OldScore>);
Marks marks{{"Asha", {78, 91}}, {"Ravi", {64}}};
Grid<char> board(2, std::vector<char>(3, '.'));
board[1][2] = 'X';
const Metres distance = 1500.0;
const Seconds time = 300.0;
const double nonsense = distance + time; // compiles: both are just double
std::println("{} students, board {}x{}, row 1 = {}, distance + time = {}", marks.size(), board.size(),
board[0].size(), std::string(board[1].begin(), board[1].end()), nonsense);
} from session import run
run("""
clang++ -std=c++23 -Wall -Wextra aliases.cpp -o aliases && ./aliases
g++-16 -std=c++23 -Wall -Wextra aliases.cpp -o aliases && ./aliases
""") Output
$ clang++ -std=c++23 -Wall -Wextra aliases.cpp -o aliases && ./aliases 2 students, board 2x3, row 1 = ..X, distance + time = 1800 $ g++-16 -std=c++23 -Wall -Wextra aliases.cpp -o aliases && ./aliases 2 students, board 2x3, row 1 = ..X, distance + time = 1800
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 aliases_session.py
Marks saves writing std::map<std::string, std::vector<std::int32_t>> everywhere, and Grid<char> is a
std::vector<std::vector<char>>. The C++ Core Guidelines recommend using over typedef (rule T.43) for these
reasons.
An alias is not a new type. Score and std::int32_t are the same type, which the first static_assert proves,
and so are Metres and Seconds: adding a distance to a time compiled and printed 1800. When two kinds of value must
never be mixed, make them different types: small structs (a later module) or an
enum class.
Step through the six names the program declares and the types behind them:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- Score and OldScore. using Score = std::int32_t; and the older typedef std::int32_t OldScore; give one type two more names. The two static_asserts prove that Score, OldScore and std::int32_t are the same type.
- A long name made short. Marks saves writing std::map<std::string, std::vector<std::int32_t>> wherever the marks of a class are passed around. marks.size() printed 2 students.
- An alias template. Grid is an alias template, which typedef cannot write: Grid<char> is std::vector<std::vector<char>>. The program printed board 2x3 and row 1 = ..X.
- Two names for double. Metres and Seconds both name double. distance + time compiled on both compilers without a warning and printed 1800: the aliases did not stop a distance being added to a time.
- No new type. An alias is never a new type, so it cannot catch a mix-up of units. Values that must not mix need types of their own, such as small structs or an enum class.
Two arrows end at std::int32_t and two at double: the compiler sees one type in each place, which is why the
static_assert lines hold and why 1800 printed without a complaint.
Key idea
using adds a name, never a type: it shortens long names and makes alias templates possible, but an alias and its
type mix freely, so metres and seconds still add up without a word.
Checkpoint
Check: Aliases made with using
Write auto when the type is plain to see, and the type when it is the point
- Use it when the type is already visible in the initializer (
auto p = std::make_unique<Order>();,auto n = static_cast<int>(x);), when the type is long and adds nothing (iterators, map entries), and when it cannot be written at all, as for lambdas. The Core Guidelines give the same advice in rule ES.11. - Add
&orconst auto&whenever you mean the original object, especially in loops. - Write the type when the exact type is the point: integer widths,
boolfromstd::vector<bool>, a value that must not narrow.
Your own declaration decides which form fits. Answer three questions about the variable you are writing: the table then rules out every form that would fail it, naming the program above that showed the failure:
Answer the questions above: the table then marks what fits your case and says why the rest does not.
| Declaration | Changes reach the original | No copy of the object | Says the exact type |
|---|---|---|---|
| auto | Poor no: p *= 2 doubled copies, and prices stayed [40, 25, 60] | Poor copies what it reads, a whole std::string for each name | Poor keeps what the initializer is: a proxy, a long, a std::size_t |
| auto& | Good yes: the same loop with auto& printed [80, 50, 120] | Good no copy: p is another name for each element | Mixed the type of the object, its const kept: const int& from cref |
| const auto& | Poor no: it only reads, and an assignment through it does not compile | Good no copy: the loop read 23 letters from 3 city names | Mixed the type of the object, with const added |
| auto&& | Good yes: auto&& r1 = x; then r1 = 5 changed x to 5 | Good no copy: it binds to a variable, and to a temporary such as 42 | Mixed int& for x, int&& for 42: correct, but hard to read in a loop |
| The type written out | Mixed only when you write a reference: int& changes the original, int copies it | Mixed a value type copies; a reference type does not | Good yes: bool copy = flags[1] is a bool, never a proxy |
How the answers decide
- “Must the code change the object it reads, such as each element of a vector?” Yes, it changes it: rules out auto and const auto&. auto changes only its copy, as the first loop over prices showed, and const auto& refuses every change.
- “Must the code change the object it reads, such as each element of a vector?” Yes, it changes it: adds a caveat to The type written out and auto&&. Both can change the original: the written type only when it is a reference such as int&, and auto&& says it less plainly than auto& in an everyday loop.
- “Must the code change the object it reads, such as each element of a vector?” No, it only reads it and “Is each object large, such as a std::string, or small, such as an int?” Large, like a std::string: rules out auto. auto copies each large object it reads; const auto& read 23 letters from 3 city names without a single copy.
- “Must the code change the object it reads, such as each element of a vector?” No, it only reads it and “Is each object large, such as a std::string, or small, such as an int?” Large, like a std::string: adds a caveat to auto&. auto& reads without copying too, but it also lets the code change what it should only read.
- “Must the code change the object it reads, such as each element of a vector?” No, it only reads it and “Is each object large, such as a std::string, or small, such as an int?” Small, like an int: Copying a small value such as an int costs next to nothing, so auto is a fine way to read it.
- “Does the exact type matter, such as an integer width or a bool from std::vector<bool>?” Yes, the type is the point: rules out auto and auto&&. auto keeps whatever the initializer is: a std::vector<bool>::reference, a long for 3,000,000,000, a std::size_t from size(). Write the type, as bool copy = flags[1] does.
- “Does the exact type matter, such as an integer width or a bool from std::vector<bool>?” Yes, the type is the point: adds a caveat to auto& and const auto&. A reference made with auto still takes its type from the initializer; only a type you write yourself names it exactly.
In short: auto for small values you only read and for types that are long or cannot be written, auto& to change
the original, const auto& to read large objects, and the type itself when the type is what matters.
Checkpoint
Check: Choosing auto, a reference or the type
Practise: predict ten types
For each declaration in the file, replace void with the type that auto or decltype deduces on that line. The
static_assert lines check every answer while the file compiles, so the exercise is solved when it builds. Write
your answers first; a failing check then shows the real type, so you can learn from each one.
// Exercise: replace each void with the type that auto or decltype deduces on the same line.
// The static_asserts at the end check every answer: it is solved when the file builds.
#include <string>
#include <type_traits>
#include <vector>
int main() {
const int limit = 10;
int count = 3;
int& ref = count;
const std::string name = "Meera";
std::vector<int> v{1, 2, 3};
std::vector<bool> bits(8);
auto t1 = limit; using answer1 = void;
auto& t2 = limit; using answer2 = void;
auto t3 = ref; using answer3 = void;
decltype(ref) t4 = count; using answer4 = void;
decltype((count)) t5 = count; using answer5 = void;
auto t6 = name.size(); using answer6 = void;
auto t7 = v[0] * 2.0; using answer7 = void;
const auto& t8 = name; using answer8 = void;
auto t9 = 'a' + 1; using answer9 = void;
auto t10 = bits[0]; using answer10 = void;
static_assert(std::is_same_v<decltype(t1), answer1>, "t1");
static_assert(std::is_same_v<decltype(t2), answer2>, "t2");
static_assert(std::is_same_v<decltype(t3), answer3>, "t3");
static_assert(std::is_same_v<decltype(t4), answer4>, "t4");
static_assert(std::is_same_v<decltype(t5), answer5>, "t5");
static_assert(std::is_same_v<decltype(t6), answer6>, "t6");
static_assert(std::is_same_v<decltype(t7), answer7>, "t7");
static_assert(std::is_same_v<decltype(t8), answer8>, "t8");
static_assert(std::is_same_v<decltype(t9), answer9>, "t9");
static_assert(std::is_same_v<decltype(t10), answer10>, "t10");
(void)t1; (void)t2; (void)t3; (void)t4; (void)t5; (void)t6; (void)t7; (void)t8; (void)t9; (void)t10;
} As given, all ten checks fail. The session counts them without showing the compiler’s messages, which contain the answers:
from session import run
run("""
# How many of the ten checks fail? grep -c counts the lines of the compiler's output that report one.
clang++ -std=c++23 -fsyntax-only predict_types.cpp 2>&1 | grep -c 'static assertion failed'
g++-16 -std=c++23 -fsyntax-only predict_types.cpp 2>&1 | grep -c 'static assertion failed'
""") Output
# How many of the ten checks fail? grep -c counts the lines of the compiler's output that report one. $ clang++ -std=c++23 -fsyntax-only predict_types.cpp 2>&1 | grep -c 'static assertion failed' 10 $ g++-16 -std=c++23 -fsyntax-only predict_types.cpp 2>&1 | grep -c 'static assertion failed' 10
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 predict_types_session.py
First hint: start from the three rules of auto (references dropped, top-level const dropped, arrays and functions
become pointers), remember that decltype keeps references, and that 'a' + 1 is computed in the type that char
is integral promotion: The conversion of an operand narrower than int, such as bool, char, unsigned char or short, to int before arithmetic, so that 200 + 100 with unsigned char operands is the int 300. More in “Integer overflow and signed/unsigned conversions” to.
Once the file builds, test yourself on all seven ideas. The questions start with the idea you have answered least well so far, and each option you pick tells you what it gets right or misses:
Practice that adapts to you
Practise this lesson
18 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · What does auto deduce for auto x = r; when r is a const int&?
It deduces int. auto deduces the type of the value, so it drops the reference and then the top-level const, and
x is a separate, modifiable copy. To keep the reference write auto& x = r;, which deduces const int& because the
const now belongs to the object referred to; const auto& x = r; says the same thing more explicitly.
decltype(r) x = r; would also give const int&.
An interviewer who hears that answer often changes one character of the declaration and asks again. Pick an answer to each of these two follow-ups, and read why each option holds or fails:
Checkpoint
Interview round: two follow-up questions
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
The loop for (auto order : orders) order.status = Status::shipped; compiles, but no order is ever marked as shipped, and a profile shows the loop spending most of its time copying. Explain both symptoms and the fix.
-
Mid to senior
A function returns std::vector<bool>, and a caller writes auto ok = check_all()[0]; and uses ok a few lines later. It seems to work in tests, but AddressSanitizer reports a heap-use-after-free. Explain why, and how to make such code safe.
Key takeaways
autodeduces the type of the initializer’s value: references and top-levelconstare dropped, arrays become pointers.auto&andconst auto&keep the original object, for elements you change or only read;auto&&binds to anything and is mostly for generic code.decltype(x)is the declared type,decltype((x))an lvalue reference, anddecltype(auto)deduces withdecltyperules.autokeeps proxy types (std::vector<bool>::reference) and literal types (longorlong long): write the type when it matters.using Name = Type;makes an alias, also for templates; an alias is not a new type.- Choose by what the code needs:
autowhere the type is plain to see or cannot be written, a reference for the original object, and the written type when the type is the point.
Terms in this lesson
- alias template
- A type alias with template parameters, such as template <typename T> using Grid = std::vector<std::vector<T>>;, which typedef cannot write.
- array-to-pointer conversion
- The implicit conversion of an array to a pointer to its first element, which happens in most uses of an array, such as auto f = scores;. The pointer no longer carries the array's length.
- forwarding reference
- A reference written auto&&, or T&& in a template whose T is deduced, that binds to anything: it becomes an lvalue reference for a named variable and an rvalue reference for a temporary.
- lvalue
- An expression that refers to an object with an identity, such as a named variable, (x) or v[0]. decltype gives a reference type, such as int&, for an lvalue that is not a plain name.
- proxy object
- An object returned in place of a reference, standing for an element that cannot be referred to directly, as std::vector<bool>::reference stands for one bit. It points into its container and is valid only while the container lives.
- top-level const
- A const that applies to an object itself, as in const int or int* const, rather than to what a pointer or a reference leads to. auto drops it, because the new variable is a separate object.
- type alias
- A second name for an existing type, made with using Name = Type; or typedef. It makes no new type, so values of the alias and of the original type mix freely.
- type deduction
- The compiler working out a type from an initializer or an argument instead of reading it from the declaration, as it does for auto, decltype(auto) and the parameters of function templates.
Corrections
- The opening now says that some deductions, such as those of the loops and of auto&&, are shown by what the programs print rather than by a static_assert.
References
- C++ Working Draft (N4950): 9.2.9.6 Placeholder type specifiers, 9.2.9.5 Decltype specifiers, 9.2.4 The typedef specifier, 7.3.3 Array-to-pointer conversion, 6.7.7 Temporary objects (ISO/IEC JTC1/SC22/WG21)
- N3922: New Rules for auto deduction from braced-init-list (ISO/IEC JTC1/SC22/WG21)
- C++ Core Guidelines: ES.11 Use auto to avoid redundant repetition of type names (Standard C++ Foundation)
- C++ Core Guidelines: T.43 Prefer using over typedef for defining aliases (Standard C++ Foundation)
- Data Type Ranges (Microsoft C++) (Microsoft)
- AddressSanitizer (LLVM Project)
Report a problem with this lesson
Kept only in this browser. Your Learn progress