Initializing Primitive Array to One Value

前端 未结 6 1364
暗喜
暗喜 2021-01-18 03:55

Is there a way to initialize an array of primitives, say a integer array, to 0? Without using a for loop? Looking for concise code that doesn\'t involve a for loop.

6条回答
  •  既然无缘
    2021-01-18 04:44

    Yes, it is possible. The initialization method depends on the context.

    If you are declaring a static or local array, use = {} initializer

    int a[100] = {};  // all zeros
    

    If you are creating an array with new[], use () initializer

    int *a = new int[100](); // all zeros
    

    If you are initializing a non-static member array in the constructor initializer list, use () initializer

    class C {
      int a[100];
    
      C() : a() // all zeros
      {
        ...
      }
    };
    

提交回复
热议问题