I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.
I could swear I once knew a simple way to do this. I could use memset()
in my case, but isn't there a way to do this that is built right into the C syntax?
Best Solution
Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there's no easy way.
Don't overlook the obvious solution, though:
Elements with missing values will be initialized to 0:
So this will initialize all elements to 0:
In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C:
Remember that objects with static storage duration will initialize to 0 if no initializer is specified:
And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)