Typedef struct vs struct? |Definition difference|
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
forstruct 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
.
solid.py
Updated on June 04, 2022Comments
-
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 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 over 10 yearsWithout the tag name, the type
flight
cannot have members of typeflight*
(because the identifierflight
isn't visible early enough). -
Cloud over 10 yearsIt might also be worth noting that a lot of software often uses the notation:
typedef struct flight { ... } flight_t
, or sometimestypedef struct flight_s { ... } flight_t
. -
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 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 over 8 years@Dogbert see books.google.com/… and stackoverflow.com/questions/1391447/…