std::unreachable
From cppreference.com
Defined in header <utility>
|
||
[[noreturn]] void unreachable(); |
(since C++23) | |
Invokes undefined behavior. 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).
Contents |
Notes
Feature-test macro | Value | Std | Feature |
---|---|---|---|
__cpp_lib_unreachable |
Possible implementation
First version |
---|
[[noreturn]] inline void unreachable() {} |
Second version |
[[noreturn]] inline void unreachable() { __builtin_unreachable(); // Compiler specific: GCC, Clang, ICC. // On MSVC could be: __assume(false); } |
Example
Run this code
#include <vector> #include <cassert> #include <cstddef> #include <cstdint> #include <utility> struct Color { std::uint8_t r, g, b, a; }; // Assume that only restricted set of the textures 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:
Segmentation fault