Say I want to initialize myArray
char myArray[MAX] = {0};
char myArray[MAX] = {0,};
char myArray[MAX]; memset(myArray, 0, MAX);
Are they all equal or any preferred over another?
Thank you
Say I want to initialize myArray
char myArray[MAX] = {0};
char myArray[MAX] = {0,};
char myArray[MAX]; memset(myArray, 0, MAX);
Are they all equal or any preferred over another?
Thank you
Actually, in C++, I personally recommend:
char myArray[MAX] = {};
They all do the same thing, but I like this one better in C++; it's the most succinct. (Unfortunately this isn't valid in C.)
By the way, do note that char myArray[MAX] = {1};
does not initialize all values to 1! It only initializes the first value to 1, and the rest to zero. Because of this, I recommend you don't write char myArray[MAX] = {0};
as it's a little bit misleading for some people, even though it works correctly.
They are equivalent regarding the generated code (at least in optimised builds) because when an array is initialised with {0}
syntax, all values that are not explicitly specified are implicitly initialised with 0, and the compiler will know enough to insert a call to memset
.
The only difference is thus stylistic. The choice will depend on the coding standard you use, or your personal preferences.
I think the first solution is best.
char myArray[MAX] = {0}; //best of all
Either can be used
But I feel the below more understandable and readable ..
char myArray[MAX];
memset(myArray, 0, MAX);
Assuming that you always want to initialize with 0.
--> Your first way and 2nd way are same. I prefer 1st.
--> Third way of memset()
should be used when you want to assign 0s other than initialization.
--> If this array is expected to initialized only once, then you can put static
keyword ahead of it, so that compiler will do the job for you (no runtime overhead)
You can use also bzero fn (write zero-valued bytes)
#include <strings.h>
void bzero(void *s, size_t n)