cmacros

Can a C macro be made to take an arbitrary list of primitive types, and work out the sum of their sizeof() values?


If sizeof() isn't evaluated at runtime, and variadic macros are possible, I was wondering if for an arbitrary list of primitive types a macro can evaluate the combined size.

As an example, I know that is is possible to do this:

#define sizeof_x(x) sizeof(x)

int main()
{
    printf("%d", sizeof_x(int));
    return 0;
}

Which will return 4. I was wondering if such a macro as below would be possible:

sizeof_types(int, int, double)
sizeof_types(int, char)
sizeof_types(float, float, float)

Or if I would have to manually definite a macro for each number of arguments I could pass

I tried using variadic arguments and expected them to take types as arguments but this didn't work


Solution

  • A macro cannot process each of it's parameters in sequence, there's no such a thing in the preprocessor. Indeed, the parameters themselves have to be considered text that is given to the actual compiler after macro expansion.

    For this reason, the c preprocessor cannot compute the sizeof operator on any of those parameters, but just adjust it to them... but as there's no looping capacity on the preprocessor, no way to produce the desired text.

    Independent of this, beware because the compiler normally applies aligning and skips some data between fields to do that.