1

In many places in code I have seen code like this:

typedef struct Name_of_Struct{
    //Things that the struct holds
} Name_of_Struct;

I don't seem to understand why such a declaration? Why is a struct typedef'ed to its own name? Isn't it like saying typedef Name_of_struct Name_of_Struct; ? I know there must be some reason behind such a declaration, as such instances of code are seen in good and highly used code bases like SDL.

The Light Spark
  • 504
  • 4
  • 19

3 Answers3

4

In C++ you don't have to do that

However in C this is done in order to save some typing

struct Name_of_Struct{
    //Things that the struct holds
} ;

struct Name_of_Struct ss; // If not typedef'ed you'll have to use `struct`

But with typedef

typedef struct Name_of_Struct{
    //Things that the struct holds
} Name_of_Struct;

Name_of_Struct ss ; // Simply just use name of struct, avoid struct everywhere
P0W
  • 46,614
  • 9
  • 72
  • 119
1

The code is probably shared between C and C++. The C Programming Language does not automatically create type names for user-created types (e.g., enum, struct, union). I haven't written a lot of C in recent years so this may have been changed in C99.

D.Shawley
  • 58,213
  • 10
  • 98
  • 113
1

Specifying the name twice is redundant.

Originally in C the typedef was used so you didn't need to qualify the name with struct all the time. In C++ you can simply name the struct.

// C method

struct MyStruct {};

// need to qualify that name with `struct`

struct MyStruct s;

// C method avoiding typing `struct` all the time

typedef struct {} MyStruct;

MyStruct s; // no need to use `struct`

// C++ way

struct MyStruct {};

MyStruct s;

It seems some programmers have made a Frankenstein of the two methods.

Galik
  • 47,303
  • 4
  • 80
  • 117