Or closer to the actual example:
Code: Select all
struct { int x, y, w, h } bg = { .x = 161, .y = 152, .w = 174, .h = 170 };
A typedef is not needed unless you are wanting to reuse the structure for other purposes. Structures are declared like:
Code: Select all
struct StructType
{
StructFields
} StructObject.
Both the StructType and StructObject parts are optional. A struct without a StructType is called an anonymous structure. If a struct declaration does not have StructObject part, you can create an instance of StructType like:
Code: Select all
struct StructType myNewStructObject;
In the early days of C, this was the only way to declare structures, but people didn't like it because it was too verbose. So the typedef keyword was introduced which allowed you to do:
Code: Select all
typedef struct StructType TypeName;
TypeName myNewStructObject;
;
It can almost be thought of as a backwards #define macro. However, people decided to be lazy and combine the two, hence the
Code: Select all
typedef struct StructType
{
StructFields
} TypeName;
where TypeName would tend to have an _t suffix, though purely optional. This usage became so popular to the point where it was the only thing taught by books and people believed it to be the only way of declaring a struct. Believe it or not, I have actually had people that tried to tell me that what I was doing, which is the original way it was done, is wrong, despite the exact opposite being the truth! Out of habbit, I declare my typedefs completely separate from my structs because it looks better with allman coding style, like:
Code: Select all
typedef struct Rect Rect;
struct Screen
{
Rect rect;
unsigned color;
};
struct Rect
{
int x, y, w, h;
};