我有一个宏,它使用 GCC 的 typeof 创建与宏参数相同类型的变量。问题是:如果这个论点有const
类型,在宏内部创建的变量是const
我无法使用它。例如:
#include <stdio.h>
#define DECR(x) ({typeof(x) y; y = x; y--; y;})
int main(void)
{
const int v = 5;
printf("%d\n", DECR(v));
return 0;
}
编译给出:
$ cc -c -o t.o t.c
t.c: In function 'main':
t.c:9:2: error: assignment of read-only variable 'y'
t.c:9:2: error: decrement of read-only variable 'y'
make: *** [t.o] Error 1
有没有办法复制值的类型并将其变为常量?
如果您不介意可能的算术提升,您可以这样做:
#define DECR(x) ({typeof(x + 0) y; y = x; y--; y;})
诀窍在于表达式typeof
is x + 0
,这是一个右值,因此左值常量(这是您想要避免的)会丢失。
同样的技巧可以用1 * x
,但奇怪的是,+x
and -x
不工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)