如何在C中使用静态断言来检查传递给宏的参数类型

问题描述 投票:0回答:1

我需要编写一个C宏来检查以确保传递给它的所有参数都是unsigned并且具有相同的整数类型。例如:所有输入参数均为uint8_t,或全部为uint16_t,或全部为uint32_t,或全部为uint64_t

这里是如何在C ++中完成这种检查的方法:Use static_assert to check types passed to macro

即使仅通过gcc扩展,在C中是否也存在类似的东西?

注意,静态断言可通过_Static_assert在gcc中使用。 (请在此处查看我的答案:Static assert in C。)>

此操作无效:

int a = 1; 
int b = 2;
_Static_assert(__typeof__ a == __typeof__ b, "types don't match");

错误:

main.c: In function ‘main’:
main.c:23:20: error: expected expression before ‘__typeof__’
     _Static_assert(__typeof__ a == __typeof__ b, "types don't match");

我需要编写一个C宏来检查以确保传递给它的所有参数都是无符号的并且具有相同的整数类型。例如:所有输入参数均为uint8_t,或全部uint16_t,或全部uint32_t,或全部...

c gcc types macros typechecking
1个回答
1
投票

[如果此处最重要的方面是如果ab是不同的类型,则您希望它无法编译,则可以使用C11的_Generic以及GCC的__typeof__扩展名来管理它。] >

一个小例子:

© www.soinside.com 2019 - 2024. All rights reserved.