8

I saw this in some C code:

Wininfo W = { sizeof(Wininfo) };

What the heck does this mean?

Hogan
  • 69,564
  • 10
  • 76
  • 117
Paul Reiners
  • 8,576
  • 33
  • 117
  • 202

3 Answers3

15

This code is initializing a struct using funky C initializer syntax to initialize each field in order of declaration, see http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=421. An important side-effect in the case of this example is that remaining fields one doesnt specify values for get initialized to zeros.

This trick is a relatively common one in Win32 APIs - the API requires the size to be pre-set as a way of indicating the version the client code is compiled against - in many of these cases, one is also expected to clear the buffer, which would ordinarily involve a separate call to e.g. memset prior to initializing the size field with the sizeof.

See also Struct initialization of the C/C++ programming language? for related examples

Community
  • 1
  • 1
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
9

It's an initializer expression that sets the first field of W to sizeof(Wininfo) and the other fields to zero.

sth
  • 222,467
  • 53
  • 283
  • 367
5

Firstly, it is not a statement, it is a declaration. Declarations are not statements in C.

Secondly, the = { /* whatever */ } part is an initializer - it specifies the initial value of an object. Normally you use initializers enclosed in {} to initialize aggregate objects: arrays or structs. However, a little-known feature of C language is that initializers of scalar objects can also be optionally enclosed in {}, as in

int i = { 5 };

What exactly your specific declaration means depends on what Wininfo type is. If W is an aggregate, then its first member is initialized with sizeof(Wininfo) value and the rest is initialized with zeroes. If W is a scalar, then it just gets the initial value of sizeof(Wininfo).

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • Since it includes an initializer, it's not just a declaration, but a definition. – Jerry Coffin Jan 11 '10 at 15:09
  • Definition is always a declaration. So, it contexts when the distinction is of no importance, the term *declaration* is normally used. The syntactic element is always called *declaration*. Definitions only exist at the level of semantics. – AnT stands with Russia Jan 11 '10 at 15:11
  • +1: Nice and complete (@nos: this is what I was angling at when mentioning redundant) – Ruben Bartelink Jan 11 '10 at 15:12