• Create Account

### #ActualWashu

Posted 23 October 2012 - 12:07 PM

The first one will print an undefined value since the integer allocated by new int is not initialized. The second one will print zero, because the integer allocated by new int() is default initialized to zero. The parentheses syntax default initializes primitive types to zero. The same goes for members; if you explicitly default initialize a primitive member of a structure or a class in the initializer list it is initialized to zero; if you omit it from the initializer list it is left with an undefined value.

This man gets the prize. Granted, that the prize is nothing makes winning this particular contest bittersweet at best.

Technically he should say unspecified value, slightly different meaning in the context of the standard language. But yes, that is one of the "great" things about C++, something as trivial and difficult to notice in the overall context of a large set of code can have a massive difference in the behavior of the application as a whole. Such as () vs no () when allocating an object or array of objects. Its even worse in the array case:

#include <iostream>
int main() {
int* p1 = new int[10];
int* p2 = new int[10]();
for(int i = 0; i < 10; ++i) {
std::cout<<p1[i]<<std::endl;
std::cout<<p2[i]<<std::endl;
}
delete [] p1;
delete [] p2;
}


Which not only looks terrible, but has additional symbols just to make it even more confusing. Ahh, the joys of C++

### #1Washu

Posted 23 October 2012 - 12:07 PM

The first one will print an undefined value since the integer allocated by new int is not initialized. The second one will print zero, because the integer allocated by new int() is default initialized to zero. The parentheses syntax default initializes primitive types to zero. The same goes for members; if you explicitly default initialize a primitive member of a structure or a class in the initializer list it is initialized to zero; if you omit it from the initializer list it is left with an undefined value.

This man gets the prize. Granted, that the prize is nothing makes winning this particular contest bittersweet at best.

Technically he should say unspecified value, slightly different meaning in the context of the standard language. But yes, that is one of the "great" things about C++, something as trivial and difficult to notice in the overall context of a large set of code can have a massive difference in the behavior of the application as a whole. Such as () vs no () when allocating an object or array of objects. Its even worse in the array case:

#include <iostream>
int main() {
int* p1 = new int[10];
int* p2 = new int[10]();
for(int i = 0; i < 10; ++i) {
std::cout<<p1[i]<<std::endl;
std::cout<<p2[i]<<std::endl;
}
delete [] p1;
delete [] p2;
}


Which not only looks terrible, but has additional symbols just to make it even more confusing. Ahh, the joys of C++

PARTNERS