Typedef for Structures and Unions
suggest changeYou can give alias names to a struct:
typedef struct Person {
char name[32];
int age;
} Person;
Person person;
Compared to the traditional way of declaring structs, programmers wouldn’t need to have struct every time they declare an instance of that struct.
Note that the name Person (as opposed to struct Person) is not defined until the final semicolon. Thus for linked lists and tree structures which need to contain a pointer to the same structure type, you must use either:
typedef struct Person {
char name[32];
int age;
struct Person *next;
} Person;
or:
typedef struct Person Person;
struct Person {
char name[32];
int age;
Person *next;
};
The use of a typedef for a union type is very similar.
typedef union Float Float;
union Float
{
float f;
char b[sizeof(float)];
};
Reading b after writing f inspects the object representation of that float. Those bytes are implementation-defined. A trap representation is not an issue for char, so this access is defined.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents