Library contents

C++ std::optional::value_or

std::optional represents either a value or its absence. value_or returns the stored value when present and otherwise returns the supplied fallback.

A simple example

std::optional::value_or

  1. Start with No integer stored
  2. Do this Read with the fallback 7
  3. Result 7
The optional supplies the fallback only when it contains no value.

Syntax

C++ syntax
reading.value_or(fallback)
Run this example in C++

Save the program as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Supply a default for a missing measurement

A dataset includes a missing or optional measurement alongside actual numerical values. Make the missing-value policy explicit so a valid zero is not discarded or silently replaced.

First output line0
lesson.cpp
#include <iostream>
#include <optional>
#include <array>

int main() {
    std::array<std::optional<int>, 2> readings{0, std::nullopt};
    for (const auto &reading : readings) std::cout << reading.value_or(-1) << '\n';
    return 0;
}
Output
0
-1

A present zero remains zero. Checking presence separately from the numeric value preserves the distinction between an empty sensor slot and a measured zero.

C++ working draft for std::optional::value_or

Advertisements

Look up a borrowed tripod

The equipment desk has a two-day loan period for a camera, but no special period for a tripod. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?

Giventripod missing · default 7 days
Worked result7

Read a room preference

The timetable stores a room choice for the choir club. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?

Givenchoir → Hall · default Studio
Worked resultHall