0

I have an array, ex:

int M[10] = { 1 };

I expected M[0] ~ M[9] will all be filled with 1, but when I printed them out, it doesn't, only M[0] is 1, others are 0.

Mark
  • 325
  • 1
  • 16

1 Answers1

4

This is a common misconception. Often you see people write things like this

int m[10] = { 0 };

To "initialise all elements to 0"; however, really that just initialises the first element to 0 and the rest are default initialised (to 0, which is why it works). Really they could've just written int m[10] = {};

You have the same problem: you initialise only the first element to 1 then the rest default to 0. You can either specify all the parameters, or use std::fill:

int m[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int n[10];
std::fill(std::begin(n), std::end(n), 1);
Tas
  • 7,023
  • 3
  • 36
  • 51
  • what if I need all elements init to 1? need a for loop to assign it? – Mark May 21 '19 at 03:29
  • 1
    If you need all elements initialised to `1`, you'd use `std::fill` or specify them all. Sorry, was that not clear? You could use a `for` loop as well but there's no reason over something like `std::fill` – Tas May 21 '19 at 03:30
  • sorry, I didn't notice that. It is clear. – Mark May 21 '19 at 03:31