gpt4 book ai didi

c - 检测宏中的整数常量表达式

转载 作者:太空狗 更新时间:2023-10-29 16:21:08 27 4
gpt4 key购买 nike

在 Linux 内核邮件列表中讨论了一个宏,该宏测试其参数是否为整数常量表达式并且本身是否为整数常量表达式。

一种不使用内置函数的特别聪明的方法,proposed by Martin Uecker (从 inspiration 中获取 glibc's tgmath.h),是:

#define ICE_P(x) (sizeof(int) == sizeof(*(1 ? ((void*)((x) * 0l)) : (int*)1)))

如果参数是整数常量表达式,则此宏展开为值为 1 的整数常量表达式,否则为 0。但是,它依赖于 sizeof(void) 被允许(并且不同于 sizeof(int)),这是一个 GNU C extension .

是否可以在不使用内置函数且不依赖语言扩展的情况下编写这样的宏?如果是,它是否评估其论点?


有关上面显示的宏的解释,请参阅:Linux Kernel's __is_constexpr Macro

最佳答案

使用相同的思路,其中 ?: 表达式的类型取决于参数是空指针常量还是普通的 void *,但要检测类型与 _Generic :

#define ICE_P(x) _Generic((1? (void *) ((x)*0) : (int *) 0), int*: 1, void*: 0)

Demo on Ideone. _Generic 是 C11 的补充,所以如果您卡在 C99 或更早的版本上,您将无法使用它。

还有 the definition of a null pointer constant 的标准链接和 the way null pointer constants interact with the type of a ?: expression :

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.

If both the second and third operands are pointers or one is a null pointer constant and the other is a pointer, the result type is a pointer to a type qualified with all the type qualifiers of the types referenced by both operands. Furthermore, if both operands are pointers to compatible types or to differently qualified versions of compatible types, the result type is a pointer to an appropriately qualified version of the composite type; if one operand is a null pointer constant, the result has the type of the other operand; otherwise, one operand is a pointer to void or a qualified version of void, in which case the result type is a pointer to an appropriately qualified version of void.

关于c - 检测宏中的整数常量表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480442/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com