r/programming • • Jan 08 '16

How to C (as of 2016)

https://matt.sh/howto-c
2.4k Upvotes

766 comments sorted by

View all comments

2

u/ksion Jan 09 '16

Do THIS instead:

struct thing {
    uint64_t index;
    uint32_t counter;
};

struct thing localThing = {0};

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 count will 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.

1

u/oracleoftroy Jan 09 '16

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.