Sign in to follow this  
andyZER0

typedef structs and structs

Recommended Posts

Is there a difference in using typedef struct { int x, y, z; char str[256]; } myStructure_t and struct myStructure_t { int x, y, z; char str[256]; } ? If so, what is it? Thanks in advance.

Share this post


Link to post
Share on other sites
In C (not C++) struct Name{}; creates a new name in a separate namespace, you can use it only like:
struct Name variable;
If you use typedef, the name is put in the type namespace, and you can use it like:
Name variable;

In C++ this trick is no longer neccessary.

Share this post


Link to post
Share on other sites
'typedef struct' is a C idiom.

In C, if you declare struct Foo {};, you have to refer to it as struct Foo, not just Foo. That is, you have to write struct Foo foovar; and int myfunc(struct Foo param).

The typedef declares a type alias that spares you from writing the struct keyword over and over again.


In C++ it is completely useless.

And even counterproductive since your compiler might give you error messages mentionning an 'unnamed struct type', which your typedef is an alias for, instead of giving it the name you'd expect it to (the typedef).

Share this post


Link to post
Share on other sites
Quote:
Original post by twanvl
In C (not C++) struct Name{}; creates a new name in a separate namespace, you can use it only like:
struct Name variable;


slight mistake, C has no concept of namespaces.

Share this post


Link to post
Share on other sites
Quote:
Original post by snk_kid
slight mistake, C has no concept of namespaces.


Actually, the term is correct, if somewhat overloaded. C struct tags name are indeed in a separate namespace from type and symbol names.

So struct foo {};, int foo; is legit.

Share this post


Link to post
Share on other sites
One strange thing is that the Doom 3 code uses the typedef idiom even though it's in C++. Just a habit left over from the days of C, perhaps?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this