当前位置: C语言 -- 标准库 -- <stddef.h> -- unreachable

unreachable宏


概要:
#include <stddef.h>
void unreachable(void);

描述:

该宏是函数式宏,会扩展为void类型表达式。调用宏unreachable表示导致该调用的特定控制流永远不会执行;程序执行不应到达这样的调用。

如果程序执行过程中到达unreachable宏调用,其行为是未定义的。

宏unreachable是面向编译器的承诺,可以消除死代码,让编译器生成更优化的机器码。


参数:
void

无参数。


返回值:

无。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
/*宏unreachable范例*/

#include <stddef.h>
#include <stdio.h>

enum suits{Spade, Heart, Club, Diamond};

/*获取花色的函数。*/
int get_suit(enum suits s)
{
  switch(s)
  {
    case Spade: return 0;
    case Heart: return 1;
    case Club: return 2;
    case Diamond: return 3;
  }
  
  unreachable();
}

int main(void)
{
    enum suits card = Club;
    printf("Card suits: %d\n", card);

    return 0;
}

可能输出:

Card suits: 2

(注:编译时实现未支持宏unreachable。)


相关内容:
NULL 表示空指针常量的宏。
offsetof 表示成员偏移值的宏。


主要参考资料:

1、ISO/IEC 9899:2024

2、gcc.gnu.org : add a way to mark that a path cannot be taken, something like __builtin_unreachable()

3、en.cppreference.com : unreachable