Initializing an object to all zeroes

Posted by dash-tom-bang on Stack Overflow See other posts from Stack Overflow or by dash-tom-bang
Published on 2010-05-14T21:51:00Z Indexed on 2010/05/14 21:54 UTC
Read the original article Hit count: 138

Filed under:
|

Oftentimes data structures' valid initialization is to set all members to zero. Even when programming in C++, one may need to interface with an external API for which this is the case.

Is there any practical difference between:

some_struct s;
memset(s, 0, sizeof(s));

and simply

some_struct s = { 0 };

Do folks find themselves using both, with a method for choosing which is more appropriate for a given application?

For myself, as mostly a C++ programmer who doesn't use memset much, I'm never certain of the function signature so I find the second example is just easier to use in addition to being less typing, more compact, and maybe even more obvious since it says "this object is initialized to zero" right in the declaration rather than waiting for the next line of code and seeing, "oh, this object is zero initialized."

When creating classes and structs in C++ I tend to use initialization lists; I'm curious about folks thoughts on the two "C style" initializations above rather than a comparison against what is available in C++ since I suspect many of us interface with C libraries even if we code mostly in C++ ourselves.

© Stack Overflow or respective owner

Related posts about c

    Related posts about c++