Introduction & Syntax
Modern C++ Features (C++11 to C++23) · Study material
Modern C++ means the language as reshaped by C++11 and every standard since – C++14, C++17, C++20 and C++23. It is a very different language from the "C with classes" many textbooks still teach: auto and range-for instead of iterator boilerplate, smart pointers instead of new/delete, std::optional and std::expected instead of magic error values, std::format and std::print instead of printf, concepts and ranges instead of cryptic templates. Companies hiring C++ developers expect this style, and interviewers routinely ask "what changed in C++11/17/20?". This page is a guided tour of the most useful features of each standard with programs you can run, then 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real compiler.
On this page
- C++11: auto, decltype, range-for, nullptr, enum class, uniform initialisation
- C++14/17: structured bindings, if/switch initialisers, optional, variant, any, string_view
- C++20: designated initialisers, consteval, constinit, using enum, <=>, std::format
- C++23: std::expected, std::print, monadic operations
- Attributes: [[nodiscard]], [[likely]], [[maybe_unused]]
The standards at a glance
| Standard | Headline features |
|---|---|
| C++11 | auto, decltype, range-for, lambdas, move semantics, smart pointers, nullptr, enum class, constexpr, variadic templates, threads, override/final, initializer lists |
| C++14 | generic lambdas, return type deduction, make_unique, digit separators, binary literals, relaxed constexpr |
| C++17 | structured bindings, if/switch initialisers, if constexpr, optional, variant, any, string_view, fold expressions, CTAD, inline variables, filesystem, parallel algorithms, guaranteed copy elision |
| C++20 | concepts, ranges, coroutines, modules, <=>, std::format, std::span, designated initialisers, consteval, constinit, jthread, using enum |
| C++23 | std::expected, std::print, deducing this, std::flat_map, ranges::to, views::zip, std::mdspan, if consteval, import std |
C++11 essentials
auto deduces a variable's type from its initialiser; decltype(expr) names the type of an expression. Range-based for walks any container. nullptr is a real null-pointer constant (so f(nullptr) picks the pointer overload, unlike f(0)). enum class creates scoped enumerations that do not convert to int implicitly. Braces give one initialisation syntax for everything. Lambdas, move semantics and smart pointers – also C++11 – have their own pages: Lambda Expressions, Move Semantics and Smart Pointers.
#include <iostream>
#include <map>
#include <string>
#include <vector>
enum class Color { red, green, blue }; // scoped: no implicit int conversion, no name clashes
enum class Status : char { ok = 'Y', fail = 'N' };
int main() {
auto n = 42; // int
auto pi = 3.14; // double
std::map<std::string, std::vector<int>> marks{{"asha", {91, 88}}, {"ravi", {72}}}; // uniform initialisation
for (const auto& entry : marks) // range-based for
std::cout << entry.first << ':' << entry.second.size() << ' ';
decltype(pi) half = pi / 2; // the type of an expression
int* p = nullptr; // a real null pointer, not 0
Color c = Color::green;
std::cout << "| " << n << ' ' << half << ' ' << (p == nullptr) << ' '
<< static_cast<int>(c) << ' ' << static_cast<char>(Status::fail) << '\n';
return 0;
}
asha:2 ravi:1 | 42 1.57 1 1 N
C++17: structured bindings and initialisers in if/switch
Structured bindings unpack pairs, tuples, arrays and structs into named variables. if (init; condition) and switch (init; value) keep helper variables inside the statement where they belong.
#include <iostream>
#include <map>
#include <string>
#include <tuple>
std::tuple<int, int, double> stats() { return {3, 91, 80.5}; }
int main() {
std::map<std::string, int> stock{{"pen", 40}, {"book", 0}};
for (const auto& [item, qty] : stock) // structured bindings
std::cout << item << '=' << qty << ' ';
auto [count, best, avg] = stats(); // unpack a tuple
std::cout << "| " << count << ' ' << best << ' ' << avg << '\n';
// if with an initialiser: 'it' exists only inside the if/else
if (auto it = stock.find("book"); it != stock.end() && it->second == 0)
std::cout << "restock " << it->first << '\n';
// insert returns a pair – bind it directly
if (auto [pos, inserted] = stock.insert({"bag", 5}); inserted)
std::cout << "added " << pos->first << '\n';
switch (int total = stock.size(); total) { // switch with an initialiser
case 3: std::cout << "three items\n"; break;
default: std::cout << total << " items\n";
}
return 0;
}
book=0 pen=40 | 3 91 80.5 restock book added bag three items
Vocabulary types: optional, variant and any
std::optional<T> holds a T or nothing – perfect for "not found" or "invalid input". std::variant<A, B> holds exactly one of several types, type-safely. std::any can hold a value of any copyable type, checked at run time.
#include <any>
#include <iostream>
#include <optional>
#include <string>
#include <variant>
// optional: a value that may be absent – no magic -1 or nullptr
std::optional<int> parse_age(const std::string& s) {
if (s.empty() || s.find_first_not_of("0123456789") != std::string::npos) return std::nullopt;
return std::stoi(s);
}
int main() {
for (std::string s : {"21", "abc"}) {
auto age = parse_age(s);
std::cout << s << " -> " << (age ? std::to_string(*age) : "invalid") << ", value_or: " << age.value_or(-1) << '\n';
}
// variant: exactly one of several types – a type-safe union
std::variant<int, std::string> id = 1042;
std::cout << std::holds_alternative<int>(id) << ' ' << std::get<int>(id) << ' ';
id = std::string("EMP-7");
std::cout << id.index() << ' ' << std::get<std::string>(id) << '\n';
// any: holds a value of any copyable type (checked at run time)
std::any box = 3.5;
box = std::string("text");
std::cout << (box.type() == typeid(std::string)) << ' ' << std::any_cast<std::string>(box) << '\n';
return 0;
}
21 -> 21, value_or: 21 abc -> invalid, value_or: -1 1 1042 1 EMP-7 1 text
std::string_view
A string_view is a read-only view of characters – just a pointer and a length – so passing and slicing text costs nothing. Use it for parameters that only read strings. It does not own its data: never return a view of a local string.
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
// string_view: a non-owning view (pointer + length). Accepts literals, std::string and substrings without copying.
std::vector<std::string_view> split(std::string_view text, char sep) {
std::vector<std::string_view> parts;
while (!text.empty()) {
auto pos = text.find(sep);
parts.push_back(text.substr(0, pos));
if (pos == std::string_view::npos) break;
text.remove_prefix(pos + 1);
}
return parts;
}
int main() {
std::string line = "2025-11-12,Asha,Pune,91";
for (auto part : split(line, ',')) std::cout << '[' << part << ']';
std::cout << '\n';
std::string_view file = "report.final.pdf";
std::cout << file.substr(file.rfind('.') + 1) << ' ' << file.starts_with("report") << file.ends_with(".txt") << '\n';
return 0;
}
[2025-11-12][Asha][Pune][91] pdf 10
C++20 highlights
Designated initialisers name the members you set; consteval functions must run at compile time and constinit variables must be initialised at compile time; using enum brings enumerators into scope; operator<=> generates comparisons; std::format brings safe, Python-style formatting. Concepts and ranges are covered in Templates and STL Algorithms and Iterators.
#include <compare>
#include <format>
#include <iostream>
#include <string>
struct Config { // designated initialisers (C++20): name the members you set
std::string host = "localhost";
int port = 80;
bool tls = false;
};
consteval int kib(int n) { return n * 1024; } // MUST be evaluated at compile time
constinit int buffer_size = kib(4); // initialised at compile time (no static-init-order problems)
enum class Day { mon, tue, wed };
const char* name(Day d) {
using enum Day; // C++20: no more Day:: in every case
switch (d) { case mon: return "Mon"; case tue: return "Tue"; case wed: return "Wed"; }
return "?";
}
struct Version {
int major, minor;
auto operator<=>(const Version&) const = default; // all six comparisons
};
int main() {
Config c{.port = 8443, .tls = true};
std::cout << std::format("{}:{} tls={}\n", c.host, c.port, c.tls);
std::cout << std::format("{:>8}|{:<6}|{:^7}|{:08.3f}|{:#x}\n", "right", "left", "mid", 3.14159, 255);
std::cout << buffer_size << ' ' << name(Day::tue) << ' ' << (Version{1, 10} > Version{1, 9}) << '\n';
return 0;
}
localhost:8443 tls=true right|left | mid |0003.142|0xff 4096 Tue 1
C++23: std::expected and std::print
std::expected<T, E> returns either a value or an error, so failures carry a reason without exceptions. Like std::optional, it has monadic helpers: transform, and_then, or_else. std::print and std::println print with format strings directly.
#include <expected>
#include <print>
#include <string>
enum class Err { empty, not_a_number, negative };
// std::expected: either a value OR an error – like optional, but says WHY it failed
std::expected<int, Err> parse_qty(const std::string& s) {
if (s.empty()) return std::unexpected(Err::empty);
if (s.find_first_not_of("-0123456789") != std::string::npos) return std::unexpected(Err::not_a_number);
int v = std::stoi(s);
if (v < 0) return std::unexpected(Err::negative);
return v;
}
const char* why(Err e) {
switch (e) { case Err::empty: return "empty"; case Err::not_a_number: return "not a number"; case Err::negative: return "negative"; }
return "?";
}
int main() {
for (std::string s : {"12", "", "x7", "-3"}) {
auto q = parse_qty(s);
if (q) std::println("'{}' -> {}", s, *q);
else std::println("'{}' -> error: {}", s, why(q.error()));
}
auto doubled = parse_qty("21").transform([](int v) { return v * 2; }); // monadic operations
std::println("{} {}", doubled.value_or(0), parse_qty("bad").value_or(0));
return 0;
}
'12' -> 12 '' -> error: empty 'x7' -> error: not a number '-3' -> error: negative 42 0
Old style vs modern style
| Old C++ | Modern C++ |
|---|---|
std::map<std::string, int>::iterator it = m.begin(); | auto it = m.begin(); |
for (size_t i = 0; i < v.size(); ++i) | for (const auto& x : v) |
NULL, 0 | nullptr |
enum Color { RED }; | enum class Color { red }; |
T* p = new T; … delete p; | auto p = std::make_unique<T>(); |
| return -1 / nullptr for "no result" | std::optional<T> / std::expected<T, E> |
union + a type tag | std::variant |
const std::string& for read-only text | std::string_view |
printf("%d %s", n, s.c_str()) | std::print("{} {}", n, s) |
typedef std::vector<int> Vec; | using Vec = std::vector<int>; |
| SFINAE / enable_if | concepts and requires |
Common mistakes
- auto dropping references and const –
auto x = vec[0];copies; writeauto&orconst auto&. - auto with braces –
auto x{1, 2};is an error andauto x = {1, 2};is an initializer_list. - Dangling string_view – a view of a temporary or a local string returned from a function.
- Dereferencing an empty optional –
*optis undefined; usevalue(),value_or()or check first. - std::get with the wrong alternative – throws std::bad_variant_access.
- Ignoring [[nodiscard]] results – the warning is telling you about a bug.
Key points to remember
- Use auto when the type is obvious or long; use const auto& in loops over objects.
- Prefer nullptr, enum class, using, and brace initialisation.
- Use structured bindings and if-initialisers for clearer code.
- optional for "maybe a value", expected for "value or error", variant for "one of these types".
- string_view for read-only text parameters – but watch lifetimes.
- std::format / std::print for output formatting.
Frequently asked questions
Which C++ standard should I learn?
Learn modern C++ (C++17 as a baseline) and use C++20/23 features your compiler supports. GCC, Clang and MSVC support nearly all of C++20 today.
Does auto make C++ dynamically typed?
No. The type is fixed at compile time from the initialiser; auto only saves you writing it.
What is the difference between optional and expected?
optional says "there may be no value"; expected says "here is the value, or here is the error explaining why not".
Where can I learn more?
Read C++ optional, variant and format and C++20 Concepts, then practise with the exercises below.