是否有可能取消常量的typeof在GCC纯C? [英] Is it possible to un-const typeof in gcc pure C?
问题描述
我有一个使用GCC的typeof运算来创建同一类型的宏参数的一个变量的宏。现在的问题是:如果这样的说法有常量
键入,宏中创建的变量常量
,我不能用它。例如:
I have a macro that uses GCC's typeof to create a variable of the same type of a macro argument. The problem is: if that argument has const
type, the variable created inside the macro is const
and I can't use it. For instance:
#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
有没有办法复制的typeof值和未常量呢?
Is there a way to copy the typeof a value and un-const it?
推荐答案
如果你不介意的可能算术推广,你可以这样做:
If you don't mind the possible arithmetic promotion you can do this:
#define DECR(x) ({typeof(x + 0) y; y = x; y--; y;})
诀窍是,的typeof
除权pression是 X + 0
,这是A R - 值,因此L值 - 常量性(这是你希望避免的)都将丢失。
The trick is that the expression for typeof
is x + 0
, which is a r-value, and so the l-value-constness (which is what you want to avoid) is lost.
相同的技巧,可以用完成1 * X
,但奇怪的是, + X
和 -x
不起作用。
The same trick can be done with 1 * x
, but curiously enough, +x
and -x
don't work.
这篇关于是否有可能取消常量的typeof在GCC纯C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!