C++17 and C++20
- C++ course
- Advanced
- Lesson 1/83
- 5 min
Learn new features of C++17 and C++20.
Introduction to modern C++
C++17 and C++20 add stronger, safer tools to the language. C++17 brings structured bindings, if constexpr, std::optional and std::variant. C++20 adds concepts, ranges and modules on top.
These releases clean up legacy APIs and tighten compile-time checks. Bugs are caught at compile time; run-time cost is often zero. Modern C++ reduces raw pointer use and makes template error messages readable.
Safe returns with std::optional
A function may or may not produce a value. std::optional<T> models this in a type-safe way. When present the value is read with *opt or opt.value(); when absent std::nullopt is returned.
Example: std::optional<int> half_even(int x) returns x/2 for even numbers and std::nullopt for odd ones. The caller checks with if (opt). This is safer than sentinel values like -1.
Practice half_even with std::optional
Write std::optional<int> half_even(int x): return x / 2 for even numbers and std::nullopt for odd ones. In main, call half_even(8), check with if (r) and print *r via std::cout.
Starter code
#include <iostream>
#include <optional>
// Write the half_even function
int main() {
auto r = half_even(8);
// Print the result
return 0;
}Sample solution
#include <iostream>
#include <optional>
std::optional<int> half_even(int x) {
if (x % 2 == 0) return x / 2;
return std::nullopt;
}
int main() {
auto r = half_even(8);
if (r) std::cout << *r;
return 0;
}Expected output
4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which feature was added in C++20?
- Concepts Correct answer
- auto type deduction
- Lambda expressions
- Range-based for loop
Explanation: Concepts were added in C++20 to constrain templates.
2 Complete the empty return
std::optional<int> half_even(int x) {
if (x % 2 == 0) return x / 2;
return ____;
}
std::optional<int> half_even(int x) {
if (x % 2 == 0) return x / 2;
return std::nullopt;
}
Explanation: std::nullopt means 'no value'.
3 Match each feature to its version
| Term | Meaning |
|---|---|
structured bindings |
Multi unpack (C++17) |
if constexpr |
Compile branch (C++17) |
concepts |
Constraint (C++20) |
ranges |
View chain (C++20) |