Introduction
A general-purpose Maybe type for representing missing values in C without NULL or sentinel values.
- Note
- Schrödinger's cat is inside a box. Until you look, you don't know if it's alive or dead. A Maybe type works the same way. It either contains a cat, meaning you have a value, or it's empty, meaning you have nothing. Instead of risking errors when there's no cat, OPTIONAL makes you handle both cases explicitly, eliminating the need for null checks or sentinel values.
Getting Started
Adding Optionals to Your Project
This library consists of one header file only. All you need to do is copy optional.h into your project, and include it.
A general-purpose Maybe type for C.
Since it's a header-only library, there is no library code to link against.
Optional Types and Variables
- OPTIONAL_STRUCT Declares an Optional struct with a default tag and the supplied type.
- OPTIONAL Returns the type specifier for Optionals with the supplied type name.
Creating Optional Objects
Basic Usage
Checking for Presence
Unwrapping Values
- OPTIONAL_USE_VALUE Returns an Optional's value.
assert(value == AVAILABLE);
- OPTIONAL_GET_VALUE Returns an Optional's value as a possibly-null pointer.
assert(*value == AVAILABLE);
- OPTIONAL_OR_ELSE Returns an Optional's value, or the supplied one.
assert(value == PENDING);
Conditional Actions
- OPTIONAL_IF_PRESENT Performs the supplied action with an Optional's value.
side_effect = 0;
assert(side_effect == 123);
- OPTIONAL_IF_PRESENT_OR_ELSE Performs either of the supplied actions with an Optional's value.
side_effect = 0;
last_error = OK;
assert(side_effect == 0);
assert(last_error == PET_NOT_FOUND);
Advanced Usage
Screening Optionals
- OPTIONAL_FILTER Conditionally transforms an Optional into an empty one.
struct pet sold = {.status = SOLD};
- OPTIONAL_FILTER_FALSY Transforms an Optional containing a falsy value into an empty one.
- OPTIONAL_FILTER_NULL Transforms an Optional containing a null pointer into an empty one.
Transforming Values
- OPTIONAL_MAP Transforms the value of an Optional.
struct pet sold = {.status = SOLD};
- OPTIONAL_FLAT_MAP Transforms an empty Optional into a different one.
struct pet sold = {.status = SOLD};
- OPTIONAL_OR Transforms an empty Optional into a different one.
Additional Info
Compatibility
Optionals rely on modern C features such as designated initializers, compound literals, and typeof.
Releases
This library adheres to Semantic Versioning. All notable changes for each version are documented in a change log.
Head over to GitHub for the latest release.

Source Code
The source code is available on GitHub.