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:

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.