#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#define typename(x) _Generic((x), /* Get the name of a type */ \
\
_Bool: "_Bool", unsigned char: "unsigned char", \
char: "char", signed char: "signed char", \
short int: "short int", unsigned short int: "unsigned short int", \
int: "int", unsigned int: "unsigned int", \
long int: "long int", unsigned long int: "unsigned long int", \
long long int: "long long int", unsigned long long int: "unsigned long long int", \
float: "float", double: "double", \
long double: "long double", char *: "pointer to char", \
void *: "pointer to void", int *: "pointer to int", \
default: "other")
#define fmt "%20s is '%s'\n"
int main() {
size_t s; ptrdiff_t p; intmax_t i; int ai[3] = {0}; return printf( fmt fmt fmt fmt fmt fmt fmt fmt,
"size_t", typename(s), "ptrdiff_t", typename(p),
"intmax_t", typename(i), "character constant", typename('0'),
"0x7FFFFFFF", typename(0x7FFFFFFF), "0xFFFFFFFF", typename(0xFFFFFFFF),
"0x7FFFFFFFU", typename(0x7FFFFFFFU), "array of int", typename(ai));
}
╔═══════════════╗
═════════════════╣ Amazeballs... ╠═════════════════════════════════════
╚═══════════════╝
size_t is 'unsigned long int'
ptrdiff_t is 'long int'
intmax_t is 'long int'
character constant is 'int'
0x7FFFFFFF is 'int'
0xFFFFFFFF is 'unsigned int'
0x7FFFFFFFU is 'unsigned int'
array of int is 'other'
3条答案
按热度按时间58wvjzkj1#
The best example I have seen启发了下面的(runnable)示例,它为彻底的自省打开了各种奇怪的可能性...
lawou6xi2#
This是一个很好的介绍。
使用新关键字实现一般选择:_Generic。语法类似于类型的简单switch语句:
_Generic( 'a', char: 1, int: 2, long: 3, default: 0)
的计算结果为2(字符常量在C中为int)。基本上,它的工作原理类似于
switch
,其中标签是类型名,针对第一个表达式(上面的'a'
)的类型进行测试,结果成为_Generic()
的求值结果。vlf7wbxs3#
我使用CLion 1.2.4,CLion现在不支持C11,因此我使用GNU C99中的以下代码代替
_Generic