Typedef struct vs struct? | Definition of difference |

The following blocks are outside of main() and before each function (global scope)

1st block:

 struct flight{ int number; int capacity; int passengers; }; 

With this you can create an array, pointer, variable, as opposed to writing }var ; (which defines only one variable of this custom data type (struct flight ))

Second block:

 typedef struct flight{ int number; int capacity; int passengers; }flight; 

Announcing this creates a flight data type without having to write struct flight all the time
My question is, why does typedef need a flight to be written a second time at the end of the block?
which is a bit confusing (it only looks like a variable of this data type)

+7
c struct definition typedef
source share
1 answer

My question is, why does typedef require a flight, which will be written a second time at the end of the block?

When you declare:

 typedef struct flight{ int number; int capacity; int passengers; }flight; 

you are actually declaring two things:

  • new type of structure struct flight
  • the name of an alias of type flight for struct flight .

The reason the type alias name with typedef appears at the end of the declaration, as for any regular declaration, because for historical reasons, the typedef was placed in the same qualifier category as the storage class specifiers (e.g. static or auto ).

Note that you can simply declare:

 typedef struct { int number; int capacity; int passengers; }flight; 

without a tag name, if you intend to use only an identifier of type flight .

+13
source share

All Articles