0 day streak
cpp / intermediate
Snippet

Functional Error Handling with Optional

std::optional represents a value that might or might not exist. It is a safer alternative to returning magic numbers (like -1) or null pointers, forcing the caller to explicitly check if a value is present.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <optional>
std::optional<int> find_even(int value) {
if (value % 2 == 0) return value;
return std::nullopt;
}
int main() {
auto result = find_even(7);
if (result.has_value()) {
std::cout << "Found: " << *result << std::endl;
} else {
std::cout << "No even value found." << std::endl;
}
// Using value_or for a default fallback
std::cout << "Result or default: " << find_even(3).value_or(0) << std::endl;
return 0;
}
Breakdown
1
return std::nullopt;
Explicitly returns a 'no-value' state to indicate failure or absence.
2
find_even(3).value_or(0)
Returns the contained value if present, otherwise returns the provided default (0).