PDA

View Full Version : constant c structs




davbeck
Oct 17, 2009, 04:03 PM
I tried to make a const NSPoint using NSMakePoint but I got errors that it wasn't a compile time constant. Makes sense that you couldn't do it but how would I do it then?



lee1210
Oct 17, 2009, 04:17 PM
const NSPoint x = {(CGFloat)1.0,(CGFloat)2.0};

For initializing a C struct, you list it's elements in a comma separated list in the order of its elements inside curly braces. In this case x will be 1.0, y will be 2.0.

-Lee

davbeck
Oct 17, 2009, 04:19 PM
Is there any worry that the struct will be rearranged in a future version or is that not something that would happen.

lee1210
Oct 17, 2009, 04:24 PM
It would be pretty sad if this happened, but it's definitely a risk. I don't believe there's a means to initialize a struct using the named members. I guess in this case as long as you were setting x and y to the same thing you'd always be safe. Otherwise... hm:

NSPoint x = NSMakePoint((CGFloat) 2.0, (CGFloat)1.0);
const NSPoint y = x;


-Lee

EDIT: Looks like there's a C99 feature, so I was wrong about not being able to initialize by named member:

const NSPoint z = {.x = (CGFloat)2.0, .y = (CGFloat) 1.0};