← C++ Index

❓ <optional> — std::optional — Nullable Values (C++17)

Represents a value that may or may not be present — a type-safe replacement for sentinel values like -1 or nullptr.

Include: #include <optional> | Namespace: std | Compile: g++ -Wall -std=c++17 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::optional<T>class templateHolds an optional value of type T
std::nulloptconstantRepresents an empty optional
std::make_optional(x)optional<T>Create an optional containing x
opt.has_value()boolTrue if optional contains a value
(bool)optboolSame as has_value()
opt.value()T &Return value; throws if empty
opt.value_or(def)TReturn value or def if empty
*optT &Dereference (UB if empty — check first)
opt.reset()voidDestroy the contained value
opt.emplace(…)T &Construct value in-place

💡 Example Program

Copy, save as demo.cpp, and compile with the command at the bottom.

#include <iostream>
#include <optional>
#include <string>
#include <vector>
using namespace std;

optional<int> find_index(const vector<string> &v, const string &target) {
    for (size_t i = 0; i < v.size(); i++)
        if (v[i] == target) return (int)i;
    return nullopt;
}

optional<double> safe_sqrt(double x) {
    if (x < 0) return nullopt;
    return sqrt(x);
}

int main() {
    vector<string> fruits = {"apple", "banana", "cherry"};

    if (auto idx = find_index(fruits, "banana"))
        cout << "banana at index " << *idx << "\n";
    else
        cout << "banana not found\n";

    if (auto idx = find_index(fruits, "durian"))
        cout << "durian at index " << *idx << "\n";
    else
        cout << "durian not found\n";

    cout << "sqrt(-4) = " << safe_sqrt(-4.0).value_or(-1.0) << "\n";
    cout << "sqrt(9)  = " << safe_sqrt(9.0).value() << "\n";
    return 0;
}
// Compile: g++ -Wall -std=c++17 -o optional_demo optional_demo.cpp

← <functional>  |  🏠 Index