0

I have read that global arrays are initialized to 0 by default. I tried experimenting with local arrays and declared one in the main function.

    int main()
    {
        int* x = new int[10];
        int i;
        for(i=0;i<10;i++)
        {
            cout<<x[i]<<" ";
        }
         return 0;
     }

I got the output as: 0 0 0 0 0 0 0 0 0 0

Are local arrays always initialized to 0? I am using CodeBlocks GCC if its of any help.

  • 1
    TL;DR of the dupe: No, not for `int`. The elements will get default initialized which for `int` means no initialization. What you are seeing is the compiler being "helpful" by zeroing the memory. debug builds do this to help find bugs in code. – NathanOliver Feb 04 '21 at 18:24
  • `int* x = new int[10];` -> no initialization `int* x = new int[10]();` -> value-initialization – MikeCAT Feb 04 '21 at 18:25
  • Only when you specify an empty initializer. Like `()` or `{}`, e.g. `new int[10]{}`. – Maxim Egorushkin Feb 04 '21 at 22:09
  • @NathanOliver Thank you. Is there a way to definitively know whether a compiler will auto-initialize arrays? – Apoorv Mullick Feb 05 '21 at 08:52
  • There are situations where you will know what the value will be, and those are detailed in the duplicate link. – NathanOliver Feb 05 '21 at 13:06

0 Answers0