0Pricing
C++ Academy · Lesson

Representing Absence with optional

Avoid null pointers.

The Problem with Null

Returning a sentinel like -1 or a null pointer to mean "no value" is fragile and easy to misuse. std::optional<T> represents "a value, or nothing" explicitly. Include <optional>.

#include <iostream>
#include <optional>
int main() {
    std::optional<int> maybe = 42;
    std::cout << *maybe << "\n";
}

An Empty Optional

Default-constructing an optional, or assigning std::nullopt, gives an empty one that holds no value.

#include <iostream>
#include <optional>
int main() {
    std::optional<int> empty;
    std::optional<int> also = std::nullopt;
    std::cout << empty.has_value() << " " << also.has_value() << "\n";
}

All lessons in this course

  1. Representing Absence with optional
  2. Accessing optional Values
  3. std::expected Basics
  4. Error Handling Patterns
← Back to C++ Academy