1

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?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
LunchMarble
  • 5,079
  • 9
  • 64
  • 94
  • See also [this interesting answer](http://stackoverflow.com/questions/252780/why-should-we-typedef-a-struct-so-often-in-c/254250#254250) to a similar question. – DarkDust Aug 04 '11 at 06:27

4 Answers4

6

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.

Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96
  • 2
    -1, Even though this is an old answer, it nevertheless is incorrect. `typedef Foo { int bar; };` is simply invalid C syntax. – Jens Gustedt Feb 07 '12 at 15:06
6

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;
caf
  • 233,326
  • 40
  • 323
  • 462
1

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;
Beep beep
  • 18,873
  • 12
  • 63
  • 78
0

when i am going to compile this code

typedef Foo { int bar; };

it says compile error

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222