Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of specifying two types when creating a typedef'd struct?

example 1:

struct T{
    int a;
};

creates the type struct T


example 2:

typedef struct {
    int a;
} T;

creates the type T


example 3:

typedef struct T{
    int a;
} T;

creates both the types struct T and T


I tend to see example 3 a lot, and I'm not sure why someone would choose it over example 1 or 2.

  • Are there any advantages you gain from doing it this way?
  • Are there reasons people do this for compatibility?
  • Is it advantageous for some kind of scoping reason?

I would like to avoid doing it the example 3 way, because it is less maintenance on the type, and it restricts multiple ways of declaring the same thing. However, I would reconsider it, if there are benefits to this "double naming" technique.

like image 753
Trevor Hickey Avatar asked Nov 23 '25 01:11

Trevor Hickey


1 Answers

I tend to see example 3 a lot, and I'm not sure why someone would choose it over example 1 or 2.

  • Are there any advantages you gain from doing it this way?

I hold this truth to be self-evident, namely that cumbersome code is cumbersome. Everyone would prefer to write

T object;

instead of

struct T object;

However, a hard-core C coder might think hey, T is a struct, better call it like that and also, it mitigates the chance for confusion you'd get when doing

struct {int a; } T; typedef int T; 
  • Are there reasons people do this for compatibility?

Yes. This way, structs in C can be used like they would be used in C++.

  • Is it advantageous for some kind of scoping reason?

no, not that I'd be aware of.

like image 71
Marcus Müller Avatar answered Nov 25 '25 00:11

Marcus Müller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!