I did some searching on this topic but couldn't find anything definitive.

Are basic types automatically initialized to 0 in C++ when allocated via new ? For example, are all values of nums guaranteed to be 0 in the code below? int *nums = new int[10];

Recommended Answers

All 7 Replies

I guess not - it still has garbage.

Did this test.

#include <cstdlib>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    int *nums = new int[10];
    
    for(int i=0;i<10;++i) cout << i << ": " << nums[i] << endl;
    
    delete [] nums;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

but like everything in c/c++ I'm sure it's compiler-dependant.

In C and C++, nothing is automatically initialized. (I'm pretty sure.)

You can use the STL fill_n() function to initialize it for you:

#include <algorithm>  // fill_n() and copy()
#include <iostream>   // cout, of course
#include <iterator>   // ostream_iterator<>
#include <limits>     // numeric_limits<>

using namespace std;

int main()
  {
  int *nums = new int[ 10 ];

  cout << "Before initialization: ";
  copy( nums, nums +10, ostream_iterator <int> ( cout, " " ) );
  cout << endl;

  fill_n( nums, 10, 42 );

  cout << "After initialization: ";
  copy( nums, nums +10, ostream_iterator <int> ( cout, " " ) );
  cout << endl;

  cout << "Press ENTER to finish";
  cin.ignore( numeric_limits <streamsize> ::max(), '\n' );

  delete[] nums;
  return 0;
  }

Hope this helps.

It needs always to be initialized otherwise its containt will be undefined.

When you define an array. The compiler only initializes the starting address of it on the stack. It only reserves the memory space as per the size specified.

>Are basic types automatically initialized to 0 in C++ when allocated via new ?
No, automatic default initialization of built-in objects doesn't happen most of the time. You'll see it with objects that have static storage duration, typically. But you can force default initialization with an explicit empty parameter list:

int *nums = new int[10]();

But you can force default initialization with an explicit empty parameter list:

int *nums = new int[10]();

That is a neat trick. Thanks.

That is a neat trick. Thanks.

No!!

It may not work properly on all the compilers. Don't do something which is undefined it may create problems in the long run.

>It may not work properly on all the compilers.
Please quote chapter and verse from the standard that proves this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.