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:
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
Elements with missing values will be initialized to 0:
int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...
So this will initialize all elements to 0:
int myArray[10] = { 0 }; // all elements 0
In C++, an empty initialization list will also initialize every element to 0.
This is not allowed with C:
int myArray[10] = {}; // all elements 0 in C++
Remember that objects with static storage duration will initialize to 0 if no
initializer is specified:
static int myArray[10]; // all elements 0
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.)
enum { HYDROGEN = 1, HELIUM = 2, CARBON = 6, NEON = 10, … };
andstruct element { char name[15]; char symbol[3]; } elements[] = { [NEON] = { "Neon", "Ne" }, [HELIUM] = { "Helium", "He" }, [HYDROGEN] = { "Hydrogen", "H" }, [CARBON] = { "Carbon", "C" }, … };
. If you remove the ellipsis…
, those fragments do compile under C99 or C11. – Jonathan Lefflermemset()
specific discussion: stackoverflow.com/questions/7202411/… I think it only works for 0. – Ciro Santilli 新疆再教育营六四事件法轮功郝海东