Initializing a struct
Just saw something in some of Raymond Chen’s sample code that made me go "Wha…?!?" in a good way. It’s a line where he initializes a classic Windows struct, MONITORINFO, which like a lot of windows structs starts with a cbSize value [to hold the structures byte size— used as a kind of version/error check].
Normally in such instances I would write [with a sigh]:
Whereas I noticed that Raymond wrote:
which achieves exactly the same effect incredibly neatly! I can’t believe I was unaware of this technique [specifically the fact that even though only the first value is specified, the entire struct in initialized to zero]. Brilliant! And you don’t even have to know the name of the stupid cbSize member!
BTW: I know I’m not the only one who uses [until now] the tedious long form— If you are a C/C++ person I hope this tidbit can save you valuable seconds as well. And if you are a legend who already uses the short form, please don’t think less of me for not seeing it myself… ;)
August 11th, 2005 at 2:23 am
Huh … i cannot understand how cbsSize is initialized in the second case … I can understand that the strcture is zeroed and the first member is set to sizeof(mi), but for cbSize … only if cbSize happends to be the first member ?
Any hint ?
( i’m lost )
August 11th, 2005 at 2:38 am
yes, cbSize [or any other struct size] is always first member, although this is purely by convention