Array Initialization

Question:
I’ve always used memset() in C to do char array initialization, but in C++ is it normal/acceptable practice to initialize a char array during declaration using this syntax?

char Temp[10] = {0};

Answer:
In C++ you normally don’t use arrays in the first place. You use a container class instead: e.g., std::vector. However, when you truly need a built-in array, such as:

char Temp[10];

you should avoid memset() if possible for two reasons: safety and maintenance. To demonstrate that, let’s look at your example again:

char Temp[10] = {0};

What would happen if we changed the size of the array like this?

char Temp[20] = {0};

Nothing. The compiler would do the right thing and initialize the array properly. This is not the case with memset(), where you must specify the size of the array explicitly. Failing to do so can cause undefined behavior.

Note, however, that you cannot initialize arrays that are allocated from the free store this way. In this case, you cannot avoid calling memset().

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: