Typedef struct vs struct? |Definition difference|

12,976

My question is why typedef needs flight to be written a second time at the end of a block?

When you declare:

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

you actually declare two things:

  • a new structure type struct flight
  • a type alias name flight for struct flight.

The reason why the type alias name with typedef appears at the end of the declaration like for any ordinary declaration is because for historical reasons typedef was put in the same specifiers category as storage-class specifiers (like static or auto).

Note that you can just declare:

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

without the tag name if you intend to only use the type identifier flight.

Share:
12,976
solid.py
Author by

solid.py

Updated on June 04, 2022

Comments

  • solid.py
    solid.py almost 2 years

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

    1st block:

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

    With this you can create array,pointer,variable in contrast with writing } var; (which defines only one variable of this custom data type (struct flight))

    2nd block:

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

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

  • Jonathan Leffler
    Jonathan Leffler over 10 years
    +1. You said 'if you intend to only use'; you could have said 'and you will only be able to use' — there is no struct flight available in the tagless version (unless it is some unrelated structure type, which would be poor coding style, but is far from impossible).
  • Keith Thompson
    Keith Thompson over 10 years
    Without the tag name, the type flight cannot have members of type flight* (because the identifier flight isn't visible early enough).
  • Cloud
    Cloud over 10 years
    It might also be worth noting that a lot of software often uses the notation: typedef struct flight { ... } flight_t, or sometimes typedef struct flight_s { ... } flight_t.
  • ouah
    ouah over 10 years
    @Dogbert but on POSIX systems *_t names are reserved by the implementation if any header used by POSIX is included.
  • Cloud
    Cloud over 10 years
    @ouah Can you elaborate more on this, or post a link? I've done a fair bit of embedded development (mainly driver dev), and haven't encountered anything that precludes the use of this convention.
  • MCG
    MCG over 8 years