Cross-compiler unreachable
hint for C, in a header-only library.
The library defines a function-like macro unreachable
.
Warning
As unreachable()
is only a hint to the optimizer, actually reaching it will not abort
the program, but instead, is undefined-behavior.
If you want a safer version, you can use the standard library's assert(0 && "unreachable")
(only check in debug build) or abort()
.
Branching:
#include <stdint.h>
#include "c_unreachable.h"
typedef enum {
COLOR_RED,
COLOR_GREEN,
COLOR_BLUE,
} color;
uint32_t color_value(color c) {
switch (c) {
case COLOR_RED: return 0xff0000;
case COLOR_GREEN: return 0x00ff00;
case COLOR_BLUE: return 0x0000ff;
default: unreachable();
}
}
Infinite loops:
#include "c_unreachable.h"
#include <stdio.h>
#include <unistd.h>
int main() {
for(size_t i = 0; ; i++) {
printf("%d seconds since launch\n", i);
sleep(1);
}
unreachable();
}
include(FetchContent)
FetchContent_Declare(
c_unreachable
GIT_REPOSITORY https://github.com/yehuthi/c_unreachable.git
GIT_TAG 600bea27090c8e5c96ce5c1d3636683005ffe690
)
FetchContent_MakeAvailable(c_unreachable)
add_executable(my_project src/main.c)
target_link_libraries(my_project c_unreachable)
- C23
unreachable
if implemented - Compiler extension
- GCC-like (GCC, Clang):
__builtin_unreachable
- MSVC-like (MSVC, Intel):
__assume(0)
- GCC-like (GCC, Clang):
- C11
_Noreturn
- None: The call to unreachable expands to nothing; the compiler is not hinted.
You can set the C_UNREACHABLE_DIAG
diagnostics macro to observe the implementation actually used.
When set, a message with the method will show in the compiler's output.
If set to 1
via an error message, 2
for warning, and 3
for message.
Negate the value to only trigger it when no method is used and the compiler cannot be hinted.
E.g. set to -1
to trigger a compilation error only when hinting was not possible (very discouraged outside
of diagnostics).