Types in C Macros

I'm trying to make my hand in C, and I thought it would be wise 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 check it as follows:

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 gccspews obscenities such as error: expected expression before 'int'mine.

I spent the whole day on this and still cannot figure out what is wrong with the code. Can anyone explain this to me?

In addition, I am not a programmer by profession. I don’t even work in IT, but this is my hobby. Therefore, if someone can tell me the best way to do this, please do so.

Thank!

+3
source share
1 answer

What you did should work, you only have two small typos:

#define vp_pack(v) ((void*)&v)
#define vp_unpack(v,t) (*((t*)v))

x v, vp_upack.

+2

Source: https://habr.com/ru/post/1782439/


All Articles