stanleyli stanleyli - 1 year ago 74
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>


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
works but the second line doesn't compile (MSVC 2012). How can I generate the field name using token concatenation?

jxh jxh
Answer Source

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


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}));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download