无法到达
来自 cppreference.com
定义在头文件 <stddef.h> 中 |
||
#define unreachable() /* 见下文 */ |
(自 C23) | |
类似函数的宏 unreachable
展开为一个 void 表达式。执行 unreachable() 会导致 未定义的行为。
实现可以使用它来优化不可能的代码分支(通常在优化构建中)或捕获它们以防止进一步执行(通常在调试构建中)。
内容 |
[编辑] 可能的实现
// Uses compiler specific extensions if possible. #ifdef __GNUC__ // GCC, Clang, ICC #define unreachable() (__builtin_unreachable()) #elifdef _MSC_VER // MSVC #define unreachable() (__assume(false)) #else // Even if no extension is used, undefined behavior is still raised by // the empty function body and the noreturn attribute. // The external definition of unreachable_impl must be emitted in a separated TU // due to the rule for inline functions in C. [[noreturn]] inline void unreachable_impl() {} #define unreachable() (unreachable_impl()) #endif |
[编辑] 示例
运行此代码
#include <assert.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> struct Color { uint8_t r, g, b, a; }; struct ColorSpan { struct Color* data; size_t size; }; // Assume that only restricted set of texture caps is supported. struct ColorSpan allocate_texture(size_t xy) { switch (xy) { case 128: [[fallthrough]]; case 256: [[fallthrough]]; case 512: { /* ... */ struct ColorSpan result = { .data = malloc(xy * xy * sizeof(struct Color)), .size = xy * xy }; if (!result.data) result.size = 0; return result; } default: unreachable(); } } int main(void) { struct ColorSpan tex = allocate_texture(128); // OK assert(tex.size == 128 * 128); struct ColorSpan badtex = allocate_texture(32); // Undefined behavior free(badtex.data); free(tex.data); }
可能的输出
Segmentation fault
[编辑] 另请参见
C++ 文档 for unreachable
|
[编辑] 外部链接
1. | GCC 文档:__builtin_unreachable
|
2. | Clang 文档:__builtin_unreachable
|
3. | MSVC 文档:__assume
|