Initialization of brackets of numeric types. Are they 0-initialized?

I would be sure that the following

int i{}; double x{}; 

initialize all variables to 0. My compiler seems to do this in all modes, but I have to be sure that this is clearly stated by the standard.

Any reference to the C ++ 11 standard is appreciated.

+7
c ++
source share
3 answers

This is indicated by the standard (all citations from N3337).

T x{}; - initialization of the list.

[dcl.init.list]/1: Initialization of a list is the initialization of an object or link from a list bound to init-init. Such an initializer is called a list of initializers, and comma-separated list initializers are called elements of a list of initializers. The list of initializers may be empty. [...]

Used definition to initialize a list:

[dcl.init.list]/3: An initialization list of an object or link of type T is defined as follows:

  • [many inapplicable rules]
  • Otherwise, if there are no elements in the initializer list, the object is initialized with a value.

Thus, the form for built-in types is initialization of values:

[dcl.init]/7: To initialize an object of type T means:

  • [not applicable rules]
  • otherwise, the object is initialized to zero.

So, now we are looking for zero initialization (yes, C ++ has many types of initialization):

[dcl.init]/5: For zero initialization of an object or link of type T means:

  • if T is a scalar type (3.9), the object is set to 0 (zero), taken as an integral constant expression, converted to T;
  • [...]

Yay, since arithmetic types are scalar types ( [basic.types]/9 , if you don't trust me), these forms initialize their objects with 0 .

+8
source share

Yes, this is guaranteed by the standard: in fact, this is done by value-initialization .

In particular, see paragraph 4) on the page: it indicates that it should be value-initialization :

Value initialization is performed in the following situations:
...
4) when a named variable (automatic, static, or thread-local) is declared with an initializer consisting of a pair of curly braces.

And on the same page, you see that the value-initialization effect for built-in types is to initialize them with 0 (my square brackets):

Value initialization effects:
...
4) Otherwise [if not a class, type without an array] the object is initialized to zero.

+3
source share

Form int i{}; called value initialization .

Abbreviated:

Value initialization effects:
[...]
4) Otherwise [if T is not a type of class or array], the object is initialized to zero.

+1
source share

All Articles