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)

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top