Sign in to follow this  

typedef structs and structs

This topic is 4780 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

This topic is 4780 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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