Issue
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;
}
Compilation gives:
$ 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
Is there a way to copy the typeof a value and un-const it?
Solution
If you don't mind the possible arithmetic promotion you can do this:
#define DECR(x) ({typeof(x + 0) y; y = x; y--; y;})
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.
The same trick can be done with 1 * x
, but curiously enough, +x
and -x
don't work.
Answered By - rodrigo Answer Checked By - Terry (WPSolving Volunteer)