use c Token-Pasting to access field in struct

c, struct

Solution

You don't need token pasting at all:

#define BUILD_FIELD(field) my_struct.field

According to the gcc manual token pasting should result in an identifier or a number after the concatenation. The error is due to the `.a` not being either.

Problem

I'm trying to use c token pasting (##) to access to struct field as below: ``` typedef struct { int a; int b; } TMP_T; #define BUILD_FIELD(field) my_struct.##field int main() { TMP_T my_struct; BUILD_FIELD(a) = 5; return 0; } ``` But got the following error during compilation: error: pasting "." and "a" does not give a valid preprocessing token I would like to add additional case to that: ``` typedef struct { int a; int b; }TMP_T; #define BUILD_FIELD(my_struct,field) my_struct.##field void func(char* name) { TMP_T tmp_str; if((name == "a") || (name == "b")) { BUILD_FIELD(tmp_str, name) = 7; printf("%d \n", BUILD_FIELD(a) ); } } int main() { func("a"); return 1; } ``` How should I use the macro to access the specific struct and field. Is it possible? or because its a pre compiled then it couldn't be defined for various fields (a,b) Thanks Moti

Original source