Namespaces
Variants
Views
Actions

std::unreachable

From cppreference.com
< cpp‎ | utility
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
Program support utilities
Program termination
(C++11)
(C++11)
Unreachable control flow
unreachable
(C++23)
Communicating with the environment
Signals
Signal types
Non-local jumps
Types
 
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

[edit] Notes

Feature-test macro Value Std
__cpp_lib_unreachable 202202L (C++23)

[edit] Possible implementation

[[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.
#ifdef __GNUC__ // GCC, Clang, ICC
    __builtin_unreachable();
#elifdef _MSC_VER // MSVC
    __assume(false);
#endif
}

[edit] Example

#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 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:

Segmentation fault

[edit] See also

C documentation for unreachable

[edit] External Links