Erik Öjebo
Erik Öjebo

Reputation: 10851

Difference between "struct foo*" and "foo*" where foo is a struct?

In C, is there a difference between writing "struct foo" instead of just "foo" if foo is a struct?

For example:

struct sockaddr_in sin;
struct sockaddr *sa;

// Are these two lines equivalent?
sa = (struct sockaddr*)&sin;
sa = (sockaddr*)&sin;

Thanks /Erik

Upvotes: 6

Views: 2822

Answers (4)

Lodle
Lodle

Reputation: 32187

It depends on how the struct is defined. If it is defined using a typedef you dont have to put the stuct keyword in front.

typedef struct 
{
//
} aStruct;

aStruct abc;

but if its not a typedef you need the struct keyword.

struct aStruct
{
//
} ;

struct aStruct abc;

Upvotes: 0

Avi
Avi

Reputation: 20142

Yes. In C (as opposed to C++), structs are in their own namespace. So if you defined a

struct sockaddr { ... }

you may not use it as

sockaddr s;
sockaddr *ps;

In order to make that legal, you may use typedef in order to import into the non-struct namespace of type names:

typedef struct sockaddr { ... } sockaddr;
sockaddr s, *p;

Upvotes: 6

Otávio Décio
Otávio Décio

Reputation: 74250

You can use just "foo" if you typedef it.

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421978

In fact, in standard "C" it's required to specify struct keyword. This is optional in C++.

This is the reason some people define structs like this:

typedef struct foo { ... } bar;

to be able to use bar instead of struct foo. However, some C compilers do not enforce this rule.

Upvotes: 12

Related Questions