"Int a = int ();" sure to give me zero?

Is int a = int(); give me zero?

How about if int is replaced with char , double , bool or pointer type?

Where is it specified in the language standard, please?

+7
source share
2 answers

Do I need int a = int(); give me zero?

Yes, the standard guarantees that it will give you zero.
This is called Initializing Values . For the int type, Value Initialization basically ends with Zero Initialization .

Where is it specified in the language standard, please?

The rules are clearly indicated in the standard in section 8.5 . I will quote the corresponding words Q here:

C ++ 03: 8.5 Initializers
Paragraph 7:

An object whose initializer is an empty set of brackets, i.e. (), must be initialized with a value.

Value initialization and zero initialization are defined in 8.5 Pair 5 as:

In value-initialize, an object of type T means:

- if T is a class type (section 9) with a constructor declared by the user (12.1), then the default constructor for T is called (and initialization is poorly formed if T does not have a default constructor available); - if T is the type of a non-unit class without a constructor declared by the user, then each non-static data element and components of the base class T are initialized with a value;
- if T is an array type, then each element is initialized with a value; - , otherwise the object is initialized to zero

In zero-initialize, an object of type T means:

- if T is a scalar type (3.9), the object is assigned the value 0 (zero) converted to T ; - if T is the type of a nonunit class, each non-static data member and each subobject of the base class is initialized to zero; - if T is a union type, objects first named as a data element are initialized to zero;
- if T is an array type, each element is initialized to zero; - if T is a reference type, initialization is not performed.

Note. Bold texts are highlighted by me.

+17
source

Yes, any built-in type is always initialized to zero during initialization by default. Keep in mind that in most scenarios, the built-in type is not initialized by default, so this does not necessarily output 0 :

 int i; std::cout << i << "\n"; 
0
source

All Articles