InsideLoop
InsideLoop

Reputation: 6255

Brace initialization of numeric types. Are they 0-initialized?

I would like to be sure that the following

int i{};
double x{};

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

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

Upvotes: 15

Views: 1307

Answers (3)

Ad N
Ad N

Reputation: 8396

Yes, this is guaranteed by the standard: this is actually performing value-initialization.

In particular, see the point 4) on the page: it states that it has to be value-initialization:

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

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

The effects of value initialization are:
...
4) Otherwise [if non-class, non-array type], the object is zero-initialized.

Upvotes: 7

TartanLlama
TartanLlama

Reputation: 65760

This is stated by the standard (all quotes from N3337).

T x{}; is list-initialization.

[dcl.init.list]/1: List-initialization is initialization of an object or reference from a braced-init-list.Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list. An initializer list may be empty. [...]

The applicable definition for list-initialization:

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

  • [lots of non-applicable rules]
  • Otherwise, if the initializer list has no elements, the object is value-initialized.

So that form for built-in types is value-initialization:

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

  • [non-applicable rules]
  • otherwise, the object is zero-initialized.

So now we're looking for zero-initialization (yes, C++ has a lot of types of initialization):

[dcl.init]/5: To zero-initialize an object or reference of type T means:

  • if T is a scalar type (3.9), the object is set to the value 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 both initialize their objects with 0.

Upvotes: 15

melak47
melak47

Reputation: 4850

The int i{}; form is called value initialization.

Abridged:

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

Upvotes: 3

Related Questions