Types in C Macros
I am trying my hand out in C and I thought it would be prudent to write the following macros:
// takes address of a variable and passes it on as a void*
#define vp_pack(v) ((void*)&x)
// takes a void pointer and dereferences it to t
#define vp_upack(v,t) (*((t*)v))
And I test it out like this:
int
main()
{
int five = 5;
char a = 'a';
vp ptr;
// Test 1
ptr = vp_pack(five);
if(vp_unpack(ptr,int) == five)
printf("Test 1 passed\n");
else
fprintf(stderr, "Test 1: all is doomed\n");
// Test 2
ptr = vp_pack(a);
if(vp_unpack(ptr,char) == a)
printf("Test 2 passed\n");
else
fprintf(stderr, "Test 2: all is doomed!\n");
}
But gcc
spews out obscenities like error: expected expression before 'int'
at me.
I've spent an entire day on this, and still can't understand, what is wrong with the code. Could any one explain this to me?
Also, I am no开发者_开发问答t a programmer by profession. I don't even work in IT, but this is my hobby. So if some one could tell me a better way to do this, please do so.
Thanks!
What you did should work, you just have two little typos :
#define vp_pack(v) ((void*)&v)
#define vp_unpack(v,t) (*((t*)v))
First line had x
instead of v
, and second was named vp_upack
.
精彩评论