Learn++ Lesson 52: The Optional Type in C++ Programming
An optional value can be represented with std::optional. It may be present or empty, which is useful when a function can return a result only for some inputs.
Lesson 52 introduces
- representing an optional integer with std::optional<int>
- returning an optional value from get_even
- checking whether an optional contains a value
- reading the contained value with *val
A small example looks like this
#include <iostream>
#include <optional>
std::optional<int> get_even(int x) {
if (x % 2 == 0) return x;
return {};
}
int main() {
auto val = get_even(10);
if (val) {
std::cout << *val;
}
return 0;
}
What you practice in the app
- Recognizing std::optional<int> as a value-or-empty result
- Returning an empty optional when the number is odd
- Checking an optional before reading its value
- Connecting the example to short mobile-friendly practice
Challenge focus
The Lesson 52 challenge asks learners to replace both placeholders with x so get_even returns 10 for an even input.
This lesson is available in the Learn++ Android app as part of short, mobile-friendly programming practice. Start learning at https://learnplusplus.online