In this article, we will see how to print the optional values in C++.
Using the value_or
We can use the value_or method to print the optional value. This method takes the value as an argument and prints it if the optional variable doesn’t have a value. let’s create an optional value using the std::optional
class provided by the C++ standard library.
Following is an example
#include <iostream>
#include <optional>
int main() {
std::optional<int> x = 42;
std::optional<int> y = std::nullopt;
std::cout << "x has value: " << x.value_or(0) << std::endl;
std::cout << "y has value: " << y.value_or(0) << std::endl;
return 0;
}
In the above example, we create two optional values: x
with the value of 42
, and y
with no value (i.e., std::nullopt
).
We use the value_or
method to print the value of the optional value. The value_or
method returns the value of the optional value if it exists, and the default value i.e. (0 as per the above example) if there is no value.
After running the above code, we get the following output:
x has value: 42
y has value: 0
In an alternative way, we can also use the has_value()
method to check if an optional value is present before printing it by using the value() method.
Following is an example:
#include <iostream>
#include <optional>
int main() {
std::optional<int> x = 42;
std::optional<int> y = std::nullopt;
if (x.has_value()) {
std::cout << "x has value: " << x.value() << std::endl;
} else {
std::cout << "x has no value." << std::endl;
}
if (y.has_value()) {
std::cout << "y has value: " << y.value() << std::endl;
} else {
std::cout << "y has no value." << std::endl;
}
return 0;
}
In the above example, the optional value ‘y‘ doesn’t have a value in it. Hence the y.has_value() returns the false and the “y has no value” message will be printed on the screen.