Using (or not using) parentheses when initializing an array
In the C ++ code I am reading, there are some arrays initialized as
int *foo = new int[length];
and some like
int *foo = new int[length]();
My quick experimentation couldn't find any difference between the two, but they are used alongside each other.
Does it make a difference if so what?
Edit; since there is a claim that the former should give undefined output here, this is a test showing the suspicious number 0s;
[s1208067@hobgoblin testCode]$ cat arrayTest.cc
//Test how array initilization works
#include <iostream>
using namespace std;
int main(){
int length = 30;
//Without parenthsis
int * bar = new int[length];
for(int i=0; i<length; i++) cout << bar[0] << " ";
cout << endl;
//With parenthsis
int * foo = new int[length]();
for(int i=0; i<length; i++) cout << foo[0] << " ";
cout << endl;
return 0;
}
[s1208067@hobgoblin testCode]$ g++ arrayTest.cc
[s1208067@hobgoblin testCode]$ ./a.out
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[s1208067@hobgoblin testCode]$
Edit 2; apparently this test was flawed, don't trust it - see answers for details
source to share
Using parentheses ensures that all elements of the array are initialized to 0. I just tried using the following code:
#include <iostream>
using namespace std;
int main(int,char*[]){
int* foo = new int[8];
cout << foo << endl;
for(int i = 0; i < 8; i++)
foo[i] = i;
delete[] foo;
foo = new int[8];
cout << foo << endl;
for(int i = 0; i < 8; i++)
cout << foo[i] << '\t';
cout << endl;
delete[] foo;
foo = new int[8]();
cout << foo << endl;
for(int i = 0; i < 8; i++)
cout << foo[i] << '\t';
cout << endl;
delete[] foo;
return 0;
}
When I compile and run this, it looks like it foo
gets allocated at the same memory location every time (although you probably can't rely on that). The complete output of this program for me is:
0x101300900
0x101300900
0 1 2 3 4 5 6 7
0x101300900
0 0 0 0 0 0 0 0
So, you can see that the second allocation foo
does not touch the allocated memory, leaving it in the same state it was in from the first allocation.
source to share
This line is default-initializes length
int
s, that is, you get a bunch int
with an undefined value:
int *foo = new int[length];
This line initializes their value , so you get all zeros:
int *foo = new int[length]();
source to share