C++ / CHAPTER 13

Optional results and interface contracts

Advanced

Represent a missing answer explicitly instead of inventing a numeric sentinel.

By the end of this chapter

  • Return optional for a possibly absent result
  • Check presence before accessing a value
  • Handle empty input without invalid access

The idea

This chapter assumes functions, vectors, and references. Sometimes a valid computation has no answer: an empty collection has no largest element. Returning zero would confuse absence with a genuine maximum of zero, and throwing may be unnecessary for an expected empty case. C++17 optional<T> holds either a T value or no value. The result type makes that possibility visible to every caller.

Check an optional before dereferencing it, or use value_or when a fallback makes sense for the caller’s task. Keep the search function’s contract separate from display policy: the function reports absence, while the interface may show a message or substitute a default. This separation makes boundary cases testable and prevents a convenient display value from leaking into later calculations as though it were real data.

C++ example
#include <iostream>
#include <optional>
#include <vector>
std::optional<int> firstPositive(const std::vector<int>& values){
 for(int x:values) if(x>0) return x;
 return std::nullopt;
}
int main(){auto answer=firstPositive({-2,0,6}); std::cout<<answer.value_or(-1)<<"\n";}
Result
6

The function returns at the first positive value. An empty or nonpositive-only vector produces nullopt rather than an invented match.

Try it yourself

Write maxValue that returns nullopt for an empty vector and otherwise returns its largest integer.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which result correctly represents a successful search whose value is zero?