For example I by convention null terminate a buffer (set buffer equal to zero) the following way, example 1:
char buffer[1024] = {0};
And with the windows.h
library we can call ZeroMemory
, example 2:
char buffer[1024];
ZeroMemory(buffer, sizeof(buffer));
According to the documentation provided by microsoft: ZeroMemory Fills a block of memory with zeros.
I want to be accurate in my windows application so I thought what better place to ask than stack overflow.
Are these two examples equivalent in logic?
Yes, the two codes are equivalent. The entire array is filled with zeros in both cases.
In the case of char buffer[1024] = {0};
, you are explicitly setting only the first char
element to 0
, and then the compiler implicitly value-initializes the remaining 1023 char
elements to 0
for you.
In C++11 and later, you can omit that first element value:
char buffer[1024] = {};
char buffer[1024]{};