Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct zero initialization methods

Tags:

c

memset

Is

struct datainfo info = { 0 };

the same as

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

What's the difference and which is better ?

like image 727
BigDongle Avatar asked Dec 22 '25 21:12

BigDongle


1 Answers

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++.)

like image 115
Bathsheba Avatar answered Dec 24 '25 17:12

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!