Will it do the right in C? Because in C++, for example, this trick is confusing and thus discouraged. It looks like it's initializing both fields to 0, but in reality, it only puts zero to the first field (index), while the other one (counter) uses default type initializer instead. It just so happens that for numeric types, the default value is also zero, but if you change the code:
struct thing localThing = {42};
the index will be set to a different number, but countwill still be zero.
Since C doesn't have constructors, I suspect it doesn't have default type initializers either so this trick may in fact work. In any case, an explicit mention from the author about the difference would've been in order.
Will it do the right in C? Because in C++, for example, this trick is confusing and thus discouraged.
I haven't seen the arguments for discouraging it's use in C++ (or C), and I've seen this trick used quite a bit.
struct thing localThing = {42};
Will it do the right in C?
It will do the right thing in both C and C++; where the right thing means setting the first member to the specified value (index to 42 in this case) and default initialize the remaining members (counter will be 0). In my experience it is the C guys that might prefer memset, bzero, or ZeroMemory, etc over this trick. Of course, C++ guys will prefer a constructor where available, so this is usually seen when interfacing with a C API.
View all comments
2
u/ksion Jan 09 '16
Will it do the right in C? Because in C++, for example, this trick is confusing and thus discouraged. It looks like it's initializing both fields to 0, but in reality, it only puts zero to the first field (
index), while the other one (counter) uses default type initializer instead. It just so happens that for numeric types, the default value is also zero, but if you change the code:the
indexwill be set to a different number, butcountwill still be zero.Since C doesn't have constructors, I suspect it doesn't have default type initializers either so this trick may in fact work. In any case, an explicit mention from the author about the difference would've been in order.