cstruct

Struct tag alias


Is there a way to alias a struct tag? As in, I have a struct foo and want to alias it to struct bar. I tried typedef struct foo struct bar, typedef struct foo bar, etc... but it doesn't work of course because foo and bar are not type names but tags.

Is there a way to do this without defining actual type names for my structures (I would like to keep them as tags as I am partial to prefixing them with struct - please, no religious wars over this).

My guess is tags must be unique and so it isn't possible directly but I curiously could not find a reference online (all I find are, unsurprisingly, discussions about what typedef struct means and when/why to use it, which again isn't what I'm looking for).


Solution

  • You can use #define bar foo to achieve what you want. Don't know if it's good enough for you, but it works, as it does in the following example:

    #include <stdio.h>
    
    struct foo {
        int a;
    };
    
    #define bar foo
    
    int main( ) {
    
        struct bar x;
    
        x.a = 10;
        printf( "%d", x.a );
    
        putchar( 10 );
        return 0;
    }
    

    It has one downside I can tell, which is that right now you can define, let's say, an integer with the identifier name foo, but attempting to do so with the name bar will again result in a variable with the identifier name foo, since that's how #define works.