0Pricing
C++ Academy · Lesson

std::expected Basics

Return values or errors.

std::expected Basics is a free C++ Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Values or Errors

std::expected<T, E> (C++23) holds either a successful value of type T or an error of type E. Unlike optional, it carries why it failed. Include <expected>.

Returning Success

On success you return the value directly; it is stored as the "expected" type T.

#include <expected>
#include <iostream>
std::expected<int, std::string> parse(bool ok) {
    if (ok) return 100;
    return std::unexpected("bad input");
}
int main() {
    auto r = parse(true);
    if (r) std::cout << *r << "\n";
}

Returning an Error

Wrap the error in std::unexpected(...) to signal failure while still returning the same type.

#include <expected>
#include <iostream>
#include <string>
std::expected<int, std::string> div(int a, int b) {
    if (b == 0) return std::unexpected("divide by zero");
    return a / b;
}
int main() {
    auto r = div(8, 0);
    if (!r) std::cout << r.error() << "\n";
}

Checking Success

Test the result in a boolean context or with has_value(). True means it holds the value, false means it holds the error.

#include <expected>
#include <iostream>
int main() {
    std::expected<int, int> r = 5;
    std::cout << r.has_value() << "\n"; // 1
}

Reading the Value

Use *r or r.value() to read the success value. value() throws std::bad_expected_access if it actually holds an error.

#include <expected>
#include <iostream>
int main() {
    std::expected<int, std::string> r = 7;
    if (r) std::cout << r.value() << "\n";
}

Reading the Error

When the result is in the error state, r.error() gives you the error object.

#include <expected>
#include <iostream>
#include <string>
std::expected<int, std::string> f() { return std::unexpected("nope"); }
int main() {
    auto r = f();
    if (!r) std::cout << "error: " << r.error() << "\n";
}

value_or Fallback

Just like optional, value_or(fallback) returns the success value or a default without inspecting the error.

#include <expected>
#include <iostream>
std::expected<int, std::string> f() { return std::unexpected("x"); }
int main() {
    std::cout << f().value_or(0) << "\n"; // 0
}

Optional vs Expected

std::optional says "value or nothing"; std::expected says "value or a described error". Choose expected when callers need to know the reason for failure.

Rich Error Types

The error type E can be an enum, a struct, or a message string, whatever best describes failures in your domain.

#include <expected>
#include <iostream>
enum class Err { NotFound, Denied };
std::expected<int, Err> get(bool ok) {
    if (ok) return 1;
    return std::unexpected(Err::Denied);
}
int main() {
    auto r = get(false);
    if (!r) std::cout << (int)r.error() << "\n";
}

No Exceptions Needed

std::expected lets you propagate failures as ordinary return values, useful where exceptions are disabled or costly.

Availability Note

std::expected is a C++23 feature; ensure your compiler and standard flag (for example -std=c++23) support it before using.

Quick Check

Check your understanding of std::expected.

Recap

You learned std::expected:

  • Holds either a value (T) or an error (E).
  • Return success directly, errors via std::unexpected.
  • Read with */value() and error().
  • Carries the failure reason, unlike optional.

Frequently asked questions

Is the “std::expected Basics” lesson free?

Yes — the full text of “std::expected Basics” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “std::expected Basics”?

Return values or errors. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “std::expected Basics” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Representing Absence with optional
  2. Accessing optional Values
  3. std::expected Basics
  4. Error Handling Patterns
← Back to C++ Academy