4

Consider the following code:

#include <iostream>

using namespace std;

int main(){
  int* p = new int[2];
  for (int i = 0; i < 2; i++)
    cout << p[i] << endl;  
  return 0;
}

I run it several times. It always produces the following output:

0
0

Can I assume that C++ default-initialization set array elements to its default value? In this case, can I assume that p's element values are always set to 0?

I have read the following related questions. But they does not specifically address my case:

Community
  • 1
  • 1
Jingguo Yao
  • 7,320
  • 6
  • 50
  • 63

1 Answers1

11

Can I assume that C++ default-initialization set array elements to its default value?

No, for default initialization:

  • if T is an array type, every element of the array is default-initialized;

and the element type is int, then

  • otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

On the other hand, list initialization(since C++11) like int* p = new int[2]{}; or int* p = new int[2]{0};, or value initialization like int* p = new int[2](); will guarantee that, for int all the elements will be zero-initialized.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405