2

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?

4
  • Why would you need to call an API function here when the C++ language does all you need. Commented Oct 19, 2020 at 13:50
  • 1
    @DavidHeffernan Sometimes just to make it blindingly obvious ;-) Commented Oct 19, 2020 at 17:44
  • In fact, the C++ compiler is likely to convert the first (portable, standard) syntax into the appropriate API call for fast zeroing. Commented Oct 19, 2020 at 19:59
  • The sdk often just defines ZeroMemory to use memset. Commented Oct 19, 2020 at 20:33

1 Answer 1

1

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]{}; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.