I was wondering if it is possible to iterate over arguments passed to a variadic macro in C99 or using any GCC extensions ?
For e.g. is it possible to write a generic macro that takes a structure and its fields passed as arguments and prints offset of each field within the structure ?
Something like this:
struct a {
int a;
int b;
int c;
};
/* PRN_STRUCT_OFFSETS will print offset of each of the fields
within structure passed as the first argument.
*/
int main(int argc, char *argv[])
{
PRN_STRUCT_OFFSETS(struct a, a, b, c);
return 0;
}
Here is my homework of the day, it’s based on macro tricks and today I particularly learnt about
__VA_NARG__invented by Laurent Deniau. Anyway, the following sample code works up to 8 fields for the sake of clarity. Just extend the code by duplicating if you need more (this is because the preprocessor doesn’t feature recursion, as it reads the file only once).which prints out:
EDIT: Here is a slightly different version that tries to be more generic. The
FOR_EACH(what, ...)macro applieswhatto every other argument in the variable argument list.So, you just have to define a macro that takes a single argument like this:
which is going to be applied to every argument in the list.
So, for your typical example you need to hack a bit but it still remains concise:
And you apply it like this:
Finally, a complete sample program: