std::unreachable(3)
π NAME π
okay so this is the std::unreachable(3) page from the C++ Standard Library, bestie. The NAME is literally std::unreachable - std::unreachable β no extra lore, no cap. π
β¨ Synopsis β¨
Defined in header <utility>
[[noreturn]] void unreachable(); (since C++23)
Calling this invokes undefined behavior. Like, actual UB, not a vibe check. An implementation may use this to optimize impossible code branches away (typically, in optimized builds) or to trap them to prevent further execution (typically, in debug builds). periodt. π«Ά
π§ Notes π§
feature-test macro check, because of course thereβs one:
__cpp_lib_unreachableβ Value:202202L; Std:(C++23); Feature:std::unreachable
π οΈ Possible implementation π οΈ
hereβs one possible implementation, and itβs giving compiler-specific extension energy:
[[noreturn]] inline void unreachable()
{
// Uses compiler specific extensions if possible.
// Even if no extension is used, undefined behavior is still raised by
// an empty function body and the noreturn attribute.
#if defined(_MSC_VER) && !defined(__clang__) // MSVC
__assume(false);
#else // GCC, Clang
__builtin_unreachable();
#endif
}
πΈ Example πΈ
run this code, bestie:
// Run this code
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <utility>
#include <vector>
struct Color { std::uint8_t r, g, b, a; };
// Assume that only restricted set of texture caps is supported.
void generate_texture(std::vector<Color>& tex, std::size_t xy)
{
switch (xy)
{
case 128: [[fallthrough]];
case 256: [[fallthrough]];
case 512: /* ... */
tex.clear();
tex.resize(xy * xy, Color{0, 0, 0, 0});
break;
default:
std::unreachable();
}
}
int main()
{
std::vector<Color> tex;
generate_texture(tex, 128); // OK
assert(tex.size() == 128 * 128);
generate_texture(tex, 32); // Results in undefined behavior
}
π Possible output π
and the possible output is giving yikes:
Segmentation fault
π See also π
[[assume(expression)]](C++23) β specifies that the expression will always evaluate to true at a given point (attribute specifier)assume_aligned(C++20) β informs the compiler that a pointer is aligned (function template)- C documentation for
unreachable
π External Links π
- GCC docs:
__builtin_unreachable - Clang docs:
__builtin_unreachable - MSVC docs:
__assume
mwah π this page came from http://cppreference.com, dated 2024.06.10. slay β¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms