Thomas
Thomas

Reputation: 3381

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).

Upvotes: 2

Views: 237

Answers (2)

egur
egur

Reputation: 7960

You can't typedef one struct into another but you can use typedefs to create sereval type names that point to the same type.

In similar cases what's usually being done is to use 2 typedef of the same struct:

// the one and only struct definition
struct foo {
    int x;
};

// define the new types which are equivalent to struct foo
typedef struct foo foo;
typedef struct foo bar;

// or:
typedef struct foo foo, bar;

// this is illegal:
typedef struct foo struct bar;

// create instances of the same struct
struct foo a;
foo b;
bar c;

Upvotes: 1

Utkan Gezer
Utkan Gezer

Reputation: 3069

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.

Upvotes: 1

Related Questions