stanleyli stanleyli - 4 months ago 20
C Question

Why token concatenation doesn't work in C++?

I have the following piece of code and I want to programmatically access the fields of the struct:

#include <stdio.h>
#include <stddef.h>

#define FIELD(NAME, NUM) {NAME##NUM}


struct SFOO
{
int i;
float f1;
float f2;
char c;
};

int main() {
printf("Offset of 'f1' is %u", offsetof(SFOO, f1));
printf("Offset of 'f1' is %u", offsetof(SFOO, FIELD(f, 1)));
}


The first line in
main()
works but the second line doesn't compile (MSVC 2012). How can I generate the field name using token concatenation?

jxh jxh
Answer

Get rid of the { and } in your definition of FIELD.

#define FIELD(NAME, NUM)  NAME##NUM

With your previous definition, your print statement would expand into something that the offsetof macro won't accept:

    printf("Offset of 'f1' is %u", offsetof(SFOO, {f1}));