What's the difference between these two declarations? struct x1 { ... }; typedef struct { ... } x2;
For practical purposes, nothing really. They both give a name to the struct.
typedef creates an alias for another type. For instance you can do:
- typedef int number;
-
number myNum = 10; // same as saying "int myNum = 10;"
number is now an alias for type int.
typedef struct {} x2; creates an alias for a type as well. Instead of being an alias for an int, it's an alias for the struct you just defined.
I think C differs from C++ in that you have to use the struct keyword when declaring variables of a struct type:
- struct x1 { };
-
struct x1 myX1Struct;
The typedef gets around that.