cc-preprocessor

Accessing structure member that is identical to macro name


Is there a way to access a structure member which is identical to a macro name? Consider this code:

struct test {
      int foo;
};

#define foo bar

int main(int argc, char *argv[])
{
    struct test t;
    t.foo = 5;
    return 0;
}

This code will obviously fail to compile because bar is not a member of struct test. In this question it is described that putting a function name in parentheses will disable macro expansion. So I thought that maybe this is possible with structures too and I've tried the following:

t.(foo) = 5;

But it didn't work. That's why I'd like to ask the question if it's possible to access the foo member even though there is a macro that has the same name or can I only access the structure member foo by undefining the macro foo first?

Ideally, I'm looking for a portable solution but anything that works with gcc is also fine.


Solution

  • anything that works with gcc

    If you really want to preserve the macro, just:

    struct test {
          int foo;
    };
    
    #define foo bar
    
    int main(int argc, char *argv[])
    {
        struct test t;
    #pragma push_macro("foo")
    #undef foo
        t.foo = 5;
    #pragma pop_macro("foo")
        return 0;
    }