7

I am wondering how does int array[10]={0} really work?

Does it go all the way through the entire array like this?

for(int i=0;i<10;i++) array[i]=0;

Or is it more efficient?

crazy_balance
  • 139
  • 1
  • 7

2 Answers2

2

Depends on the scope of your variable.

  1. Global scope - array will be placed in the .bss segment and zeroed before call to the main function. Is it faster? It is definitely different as zeroing takes place before the main start
  2. Local scope - the {0} initialisation will be IMO faster as those internal routines are well optimised for the particular hardware. I have tested with gcc & VS and it is quicker - but of course there is no guarantee that your compiler will do it the same way. https://godbolt.org/g/JdTPHJ
0___________
  • 60,014
  • 4
  • 34
  • 74
2

Using {0} is one of the most misleading things in C++.

int array[10]={n1, n2, n3};

This will fill the first three elements with the values in {}. The rest of the array will be initialized with the default value - 0 for int.

int array[10]={1}; // [1, 0, 0, 0...]

It's better to use

int array[10]={}; // [0, 0, 0, 0...]
Sergei
  • 508
  • 7
  • 13
  • 3
    How is this even answering the question? And empty initializer is not allowed in C https://stackoverflow.com/questions/17589533/is-an-empty-initializer-list-valid-c-code. How the heck it is receiving upvotes? – Eugene Sh. Sep 15 '17 at 16:40
  • @Eugene a good answer doesn't have to answer the question as long as it adds clarity. There is a wrong assumption in the question which I cleared up. – Sergei Sep 16 '17 at 22:09