c23 typeof

本文最后更新于:2024年9月28日

C23 标准新增了typeof 支持,其实就是gcc等编译器的扩展“转正”

1
2
3
typeof(int) a;//等价于 int a
typeof(int*) p;//等价于 int* p
typeof(int[3]) arr;//等价于 int arr[3]

下面给出一个可能比较有用的使用方式

1
2
3
#define pointer(T)  typeof(T *)
#define array(T, N) typeof(T [N])
array(pointer(char), 4) a;

可读性远远优于int(*a)[4]

typeoflinux 内核开发中被大量使用,比如

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
30
31
32
33
34
35
36
37
38
/*
* Check at compile time that something is of a particular type.
* Always evaluates to 1 so you may use it easily in comparisons.
*/
#define typecheck(type,x) \
({ type __dummy; \
typeof(x) __dummy2; \
(void)(&__dummy == &__dummy2); \
1; \
})

/*
* Check at compile time that 'function' is a certain type, or is a pointer
* to that type (needs to use typedef for the function type.)
*/
#define typecheck_fn(type,function) \
({ typeof(type) __tmp = function; \
(void)__tmp; \
})

/*
* swap - swap value of @a and @b
*/
#define swap(a, b) \
do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)

/**
* container_of_const - cast a member of a structure out to the containing
* structure and preserve the const-ness of the pointer
* @ptr: the pointer to the member
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*/
#define container_of_const(ptr, type, member) \
_Generic(ptr, \
const typeof(*(ptr)) *: ((const type *)container_of(ptr, type, member)),\
default: ((type *)container_of(ptr, type, member)) \
)

此外也可以参考笔者之前有关宏的文章