5

What's the difference between these two declarations in C:

typedef struct square{

   //Some fields

};

and

typedef struct{  

           //Some fields

} square;
PlayHardGoPro
  • 2,791
  • 10
  • 51
  • 90
  • I know, I have some fields in my struct, I just need to know the difference of the name on the bottom and top of the struct... – PlayHardGoPro Nov 03 '14 at 22:42
  • Possible duplicate of [Why should we typedef a struct so often in C?](http://stackoverflow.com/questions/252780/why-should-we-typedef-a-struct-so-often-in-c) – Raedwald Oct 17 '16 at 15:48

2 Answers2

10

The first declaration:

typedef struct square {
    // Some fields
};

defines a type named struct square. The typedef keyword is redundant (thanks to HolyBlackCat for pointing that out). It's equivalent to:

struct square {
   //Some fields
};

(The fact that you can use the typedef keyword in a declaration without defining a type name is a glitch in C's syntax.)

This first declaration probably should have been:

typedef struct square {
    // Some fields
} square;

The second declaration:

typedef struct {
    // Some fields
} square;

defines an anonymous struct type and then gives it the alias square.

Remember that typedef by itself doesn't define a new type, only a new name for an existing type. In this case the typedef and the (anonymous) struct definition happen to be combined into a single declaration.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
2
struct X { /* ... */ };

That create a new Type. So you can declare this new type by

struct X myvar = {...}

or

struct X *myvar = malloc(sizeof *myvar);

typdef is intended to name a type

typedef enum { false, true } boolean;
boolean b = true; /* Yeah, C ANSI doesn't provide false/true keyword */

So here, you renamed the enum to boolean.

So when you write

typedef struct X {
    //some field
} X;

You rename the type struct X to X. When i said rename, it's more an other name.

Tips, you can simply write :

typedef struct {
    //some field
} X;

But if you need a field with the same type (like in a linked list) you had to give a name to your struct

typedef struct X {
    X *next; /* will not work */
    struct X *next; /* ok */
} X;

Hope this helps :)

Edit : As Keith Thompson said, typdef is intended to create alias :)

crashxxl
  • 682
  • 4
  • 18