r/C_Programming • • 1d ago • Bravo 1

Article Zero-initialisation shenanigans

https://napcakes.nekoweb.org/posts/zero-init/
45 Upvotes

8 comments sorted by

9

u/imaami 1d ago

What about the C23 {}?

-1

u/WittyStick 21h ago

Has the same effect as {0}. Any members which aren't explicitly initialized are zero-initialized.

5

u/imaami 21h ago

Nope. {} also guarantees zero-initialization of implicit padding. That's a completely new feature.

3

u/WittyStick 21h ago

May not have been guaranteed by the standard, but that doesn't mean compilers weren't already doing this.

GCC zero-initializes anyway, even with no initializer.

4

u/imaami 20h ago

Not sure which one you mean here, {} or {0}, but the effect on padding bytes has not been consistent enough in the past: https://interrupt.memfault.com/blog/c-struct-padding-initialization

GCC zero-initializes anyway, even with no initializer.

Note that recent GCC versions default to -std=gnu23, so {} will explicitly guarantee zero-initialization of padding because that's what the standard dictates.

1

u/WittyStick 9h ago

I mean even if you do not intialize.

int array[10];

GCC still zero-initializes. It did this before C23. May not have always done, but I don't know exactly when it decided to.

The standard only says the value of uninitialized values in indeterminate. GCC zero-initializes. Clang won't though.

4

u/cosiekvfj 1d ago

good findings!!!!

2

u/LordRybec 15h ago

Zero initialization makes debugging much more difficult. Better to initialize with an uncommon pattern, so you can search for that pattern when debugging (or see it in buggy output without even having to search), to tell where variables have been created and initialized but not set to their intended value yet. Zeroes are too common to be used like this.