How can I zero a 2D array in C++? Do I need two for loops just for that?
Coming from other higher languages, I wonder why C++ doesn’t initialize arrays to meaningful/sensible defaults? Do I always need to declare an array then “zero” it out right afterwards?
C++ language tries to follow the principle of “you don’t pay for what you don’t use”. It doesn’t initialize fundamental types to any default values because you might not want it to happen. In any case, the language provides you the opportunity to explicitly request such initialization.
At the moment of declaration you can use initializers and simply do this
or, for a dynamically allocated array
and this will give a zero-initialized array. No loops necessary.
But if you want to zero-out an existing array, then you will indeed have to use something more elaborate. In case of integer types a good old
memsetwill work. For pointer or floating-point types the situation is in general case more complicated.memsetmight work or it might not work, depending on the implementation-defined properties. In any case, the standard library can help you to reduce the number of explicit loops by providing such loop wrappers asstd::fill.