Search code examples
cmemset

Struct zero initialization methods


Is

struct datainfo info = { 0 };

the same as

struct datainfo info;
memset(&info, 0, sizeof(info));

What's the difference and which is better ?


Solution

  • The first one is the best way by a country mile, as it guarantees that the struct members are initialised as they would be for static storage. It's also clearer.

    There's no guarantee from a standards perspective that the two ways are equivalent, although a specific compiler may well optimise the first to the second, even if it ends up clobbering parts of memory discarded as padding.

    (Note that in C++, the behaviour of the second way could well be undefined. Yes C is not C++ but a fair bit of C code does tend to end up being ported to C++.)