3

I was wondering why you would use the specifier typedef on the types struct and union, because aren't they somewhat used to define your own type anyways?

Thanks!

13
  • 3
    That's a C thing, not a C++ thing. Commented May 5, 2017 at 23:28
  • @user2357112, sure? I mean, I have seen it been used in C++? Commented May 5, 2017 at 23:29
  • The question does apply to C++ but maybe tag it C as well? Commented May 5, 2017 at 23:33
  • Seen it used by whom and in what context? Commented May 5, 2017 at 23:33
  • 1
    Probably because older c++ programmers all started with C, and got in the habit of doing this, even though it is not needed in c++. Commented May 5, 2017 at 23:35

1 Answer 1

3

Edit Reading the standard the 'typedef' isn't required in C++ and is probably there for backward compatibility. Also, with 'typedef' the code would compile in both C and C++ compilers without change or '#if define' around it so it's probably a legacy code support thing.

I think people do it to save on typing! We're a lazy lot afterall. So instead of:-

struct SomeStruct { // some data }; struct SomeStruct first_instance; struct SomeStruct second_instance; 

you'd have this instead:-

typedef struct typedefSomeStruct { // some data } SomeStruct; SomeStruct first_instance; SomeStruct second_instance; 

So when you declare instances of the type you don't need to prefix the 'struct' keyword.

Sign up to request clarification or add additional context in comments.

3 Comments

This is really a holdover from C, as C++ doesn't require the struct keyword when declaring them.
This is tagged C++, you don't need to prefix it either way
This answer doesn't work for C++.