Reputation: 41665
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
Upvotes: 43
Views: 45606
Reputation: 210352
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.
Upvotes: 49
Reputation: 1237
You can use also bzero fn (write zero-valued bytes)
#include <strings.h>
void bzero(void *s, size_t n)
http://linux.die.net/man/3/bzero
Upvotes: 0
Reputation: 44473
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.
Upvotes: 27
Reputation: 69978
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)
Upvotes: 1
Reputation: 31722
Either can be used
But I feel the below more understandable and readable ..
char myArray[MAX];
memset(myArray, 0, MAX);
Upvotes: 1
Reputation: 361302
I think the first solution is best.
char myArray[MAX] = {0}; //best of all
Upvotes: 6