gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Populating structs

#14227 - poslundc - Sat Jan 03, 2004 12:06 am

Okay, say I have a struct, I can use typecasting to populate its contents when declaring a variable. eg:

Code:
typedef struct Rect
{
   int x, y, w, h;
}
Rect;

Rect r = (Rect) {10, 15, 32, 32};


You can even do this with structs-within-structs, arrays of structs, etc.

Some of my structs are getting extremely bulky and complicated, however, and this method is becoming more unwieldy. In one case a struct with about 10 members includes another struct as a member, and that struct has another 15 members or so.

I don't want to have to populate both structs in a single line of code, but it doesn't seem like I can do only a partial declaration (ie. omit some of the members), unless I want to assign each member individually with its own assignment statement (which would just be a royal pain of the opposite kind).

Anyone know of an effective way of dealing with structs when they start to get like this? (Replacing the struct-within-struct with a pointer is not an option in this case.) Or is there some C syntax that can deal with this that I am unaware of?

Thanks,

Dan.

#14229 - sajiimori - Sat Jan 03, 2004 12:24 am

You can do partial initialization.
Code:

struct Blah { int a, b, c; };
struct Blah asdf = { a: 5, c: 10 };   // b will be 0

#14237 - poslundc - Sat Jan 03, 2004 2:31 am

Holy canole. The things I wish I'd know ten years ago.

Dan.

#14270 - tepples - Sat Jan 03, 2004 4:35 pm

Except ten years ago, partial initialization didn't exist. It's a new feature of ISO C99.

Read more about C99
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#14298 - Paul Shirley - Sat Jan 03, 2004 11:57 pm

It has however existed as a gcc extension since long before C99.