This is probably something really stupid that I’m doing wrong, but I can’t figure out what it is.
I have a struct PDRect, the members of which are a PDPoint and PDSize:
typedef struct {
GLfloat x, y;
} PDPoint;
typedef struct {
GLfloat width, height;
} PDSize;
typedef struct {
PDPoint origin;
PDSize size;
} PDRect;
When I instantiate one, like so:
PDRect rect = {
.origin = {
.x = 0,
.y = 0
},
.size = {
.height = .5,
.width = .5
}
};
the debugger says that rect.origin.width and rect.origin.height both exist and equal 0, and rect.size.x and rect.size.y both exist and equal .5. I don’t know why this is happening.
EDIT FOR CLARITY: My confusion is why rect.origin (which is a PDPoint) has height and width values associated with it and rect.size (which is a PDSize) has x and y values associated with it. Shouldn’t the origin just have x and y and size just have height and width?
EDIT: It actually fixed it to have them declared non-anonymously, i.e.:
typedef struct _PDPoint {
GLfloat x, y;
} PDPoint;
typedef struct _PDSize {
GLfloat width, height;
} PDSize;
typedef struct _PDRect {
PDPoint origin;
PDSize size;
} PDRect;
I’m still not sure I actually understand why that would make a difference, but it seems to have resolved the issue.
I think the problem happened cause you were using anonymous structs and typedefing at the same time. When a C compiler sees the
construct it actually changes is it to
Now here is what i think is happening:… and i say i think cause i can’t reproduce your example. i just changed the types to floats and run it on FreeBSD amd64/gcc version 4.2.1 20070831. code below.
outputs
as it should…
If you could try the following it would be interesting. change one of the structs to hold
integers and see if the swapping is happening again. Also try to initialize the 2 fields to something non-zero to check if you are causing it or its the default assigned value.
What i think is going on is that with your code the compiler does things in that order:
a)It sees a struct called anonymous that takes 2 floats , stores it in a stack and names it PDPoint
b)It sees a struct called anonymous that takes 2 floats , stores it in the stack and names it PDSize
c)While looking up PDPoint to define the third struct it pop()s from the stack the struct called anonymous that takes 2 floats. but at this point this resolves to PDSize.
d)for PDSize ony PDPoint is left on the stack and indeed its a struct called anonymous that takes 2 floats. 😉
The proper way to typedef and declare structs is
although some will argue that nowdays you can ditch the _t convention (and it is reserved for POSIX).
tl;dr: be careful with anonymous structs.