Nullable Values using std::optional

Checking if a std::optional has a value

What are the different ways to check if a std::optional contains a value?

Illustration representing computer hardware

There are several ways to check if a std::optional contains a value:

has_value()

This is an explicit way to check. It returns true if the optional contains a value, and false if it is empty.

#include <iostream>
#include <optional>

int main() {
  std::optional<int> maybe_int = 10;
  if (maybe_int.has_value()) {
    std::cout << "has value" << std::endl;
  } else {
    std::cout << "no value" << std::endl;
  }
}
has value

operator bool()

std::optional has a conversion operator to bool, so it can be used directly in boolean contexts like if statements. It returns true if the optional contains a value, and false if it is empty.

#include <optional>
#include <iostream>

std::optional<int> maybe_int = 10;
if (maybe_int) {
    std::cout << "has value" << std::endl;
} else {
    std::cout << "no value" << std::endl;
}
has value

Comparing to std::nullopt

You can directly compare an optional to std::nullopt to check if it is empty.

#include <iostream>
#include <optional>

int main() {
  std::optional<int> maybe_int = 10;
  if (maybe_int != std::nullopt) {
    std::cout << "has value" << std::endl;
  } else {
    std::cout << "no value" << std::endl;
  }
}
has value

In general, using has_value() is the most explicit and self-explanatory way. Using the bool conversion operator or comparing to std::nullopt can lead to more concise code, but it might be less obvious what the intent is.

Remember, trying to access the value of an empty optional leads to undefined behavior (if using operator* or operator->) or an exception (if using value()). Always check that the optional has a value before trying to access it.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved