在宏中检测整数常量表达式 [英] Detecting Integer Constant Expressions in Macros
问题描述
Linux内核邮件列表中有一个有关宏的讨论,该宏可以测试其参数是否为整数常量表达式,以及本身是否为整数常量表达式.
There was a discussion in the Linux kernel mailing list regarding a macro that tests whether its argument is an integer constant expression and is an integer constant expression itself.
Martin Uecker提出的一种不使用内置函数的特别聪明的方法 (从灵感. org/git/?p = glibc.git; a = blob; f = math/tgmath.h; h = a709a59d0fa1168ef03349561169fc5bd27d65aa; hb = d8742dd82f6a00601155c69bad3012e905591e1f"rel =" nofollow no'r'h,is';
One particularly clever approach that does not use builtins, proposed by Martin Uecker (taking inspiration from glibc's tgmath.h), is:
#define ICE_P(x) (sizeof(int) == sizeof(*(1 ? ((void*)((x) * 0l)) : (int*)1)))
如果参数为整数常量表达式,则此宏扩展为值1
的整数常量表达式,否则为0
.但是,它依赖于允许使用sizeof(void)
(与sizeof(int)
不同),这是
This macro expands into an integer constant expression of value 1
if the argument is an integer constant expression, 0
otherwise. However, it relies on sizeof(void)
to be allowed (and different than sizeof(int)
), which is a GNU C extension.
是否可以在没有内置函数且不依赖语言扩展的情况下编写这样的宏?如果是,它将评估其论点吗?
Is it possible to write such a macro without builtins and without relying on language extensions? If yes, does it evaluate its argument?
有关上面显示的宏的说明,请参阅: Linux内核的__is_constexpr宏
For an explanation of the macro shown above, see instead: Linux Kernel's __is_constexpr Macro
推荐答案
使用相同的思想,其中?:
表达式的类型取决于参数是空指针常量还是普通的void *
,但是检测 _Generic
:
Use the same idea, where the type of a ?:
expression depends on whether an argument is a null pointer constant or an ordinary void *
, but detect the type with _Generic
:
#define ICE_P(x) _Generic((1? (void *) ((x)*0) : (int *) 0), int*: 1, void*: 0)
在Ideone上进行演示. _Generic
是C11的补充,因此,如果您卡在C99或其他东西上以前,您将无法使用它.
Demo on Ideone. _Generic
is a C11 addition, so if you're stuck on C99 or something earlier, you won't be able to use it.
还具有空指针的定义的标准链接和空指针常量与以下类型的交互方式: ?:
表达式:
Also, have standard links for the definition of a null pointer constant and the way null pointer constants interact with the type of a ?:
expression:
一个值为0的整数常量表达式,或强制转换为void *的表达式,称为空指针常量.
An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.
和
如果第二个操作数和第三个操作数都是指针,或者一个是空指针常量,另一个是指针,则结果类型是一个指向使用两个操作数都引用的类型的所有类型限定符限定的类型的指针.此外,如果两个操作数都是指向兼容类型或兼容类型的不同限定版本的指针,则结果类型是指向复合类型的适当限定版本的指针. 如果一个操作数是一个空指针常量,则结果具有另一种操作数的类型;否则,一个操作数是指向void或void的限定版本的指针,在这种情况下,结果类型是指向void的适当限定版本的指针.
这篇关于在宏中检测整数常量表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!