LunchMarble
LunchMarble

Reputation: 5151

C structs vs typedef struct question

So my question is multifaceted.

For the purpose of understanding C (not C++) I believe the following code:

struct Foo { int bar; }; 

creates a custom type that I can use, but so does this:

typedef Foo { int bar; };

The only difference I have seen is whether or not I have to use the "struct" keyword before the variable of the type Foo. What are the differences that cause this behavior?

Upvotes: 1

Views: 1479

Answers (4)

Jeegar Patel
Jeegar Patel

Reputation: 27240

when i am going to compile this code

typedef Foo { int bar; };

it says compile error

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

Upvotes: 0

pabdulin
pabdulin

Reputation: 35255

The difference is:

struct Foo { int bar; }; 

creates structure type { int bar; } named Foo. I.e. full type name is struct Foo.

typedef Foo { int bar; };

creates alias Foo for unnamed structure type { int bar; }

However I'm not sure yours syntax is fully correct for strict C, but somehow it's OK for your compiler. Or it creates something different, but accidentaly it works, C syntax can be very tricky. Anyway second statement should be:

typedef struct { int bar; } Foo;

For further reference you can use this.

Upvotes: 6

caf
caf

Reputation: 239341

struct introduces a new type, but typedef merely creates an alias for another type. This declaration creates a new type called struct Foo:

struct Foo { int bar; }; 

This declaration is simply invalid:

typedef Foo { int bar; };

However, this declaration is valid, and creates a new, unnamed type, and also creates an alias to that type called Foo:

typedef struct { int bar; } Foo;

You can also create an alias to a named type - this creates an alias to the type struct Foo called Foo:

typedef struct Foo Foo;

These two names are completely interchangeable - you can pass a struct Foo to a function declared as taking an argument of type Foo, for example.

You can create aliases for any types, including built-in types. For example, you can create an alias for int called Foo:

typedef int Foo;

Upvotes: 6

Beep beep
Beep beep

Reputation: 19171

I believe your syntax is incorrect. typedef Foo { int bar; }; should be typedef Foo { int bar; } MyFoo;

The reason people would then use the typedef is so they can drop the struct in declarations. I.e.:

struct Foo myFoo;
//vs.
MyFoo myFoo;

Upvotes: 1

Related Questions