Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between `typedef struct X { }` and `typedef struct { } X`?

Tags:

c

struct

typedef

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

typedef struct square{

   //Some fields

};

and

typedef struct{  

           //Some fields

} square;
like image 646
PlayHardGoPro Avatar asked Nov 03 '14 22:11

PlayHardGoPro


People also ask

What is difference between struct and typedef struct?

Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.

What does typedef struct mean?

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.

Can typedef and struct have same name?

You can't "typedef a struct", that doesn't mean anything.

Should you typedef structs?

PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs. Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.


1 Answers

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.

like image 123
Keith Thompson Avatar answered Sep 23 '22 01:09

Keith Thompson