Library contents

C++ std::optional::value_or

An empty optional string can supply a readable default when the contact card is printed.

A simple example

std::optional::value_or

  1. Start with No string supplied
  2. Do this Try to read its length
  3. Result No length available
Checking for a missing value first lets the program choose a default before accessing a member.

Syntax

C++ syntax
phone.value_or(fallback)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

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

Print a label when the phone number is missing

A school prints contact cards from an enrollment form. Some families leave the optional phone field blank, so the printer needs a readable fallback before it measures or displays that field.

ResultAsk for a phone number
lesson.cpp
#include <iostream>
#include <optional>
#include <string>

int main() {
    std::optional<std::string> phone;
    std::cout << phone.value_or("Ask for a phone number") << '\n';
    return 0;
}
Output
Ask for a phone number

The missing contact follows the fallback branch, so the card still has a printable phone field.

Advertisements

Print an existing extension

A department saved its internal extension in the staff directory. Confirm that a contact value is available before printing it on a dispatch slip.

GivenExtension 204
Worked resultContact available

Flag an unfilled contact field

A delivery booking reaches reception without a contact value. Confirm that a contact value is available before printing it on a dispatch slip.

GivenMissing value
Worked resultAsk for contact

What to watch for

Calling value() on an empty optional throws bad_optional_access. Use value_or when a fallback is the intended result.

Documentation for std::optional::value_or