Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between int x{}; and int x = 0;?

I understood that int x{}; is a kind of default-initialization, but is it exactly the same as writing int x = 0; ?

like image 620
mr_T Avatar asked Mar 10 '16 08:03

mr_T


3 Answers

The result is same in this case.

int x{}; is a kind of default-initialization

Not exactly. See default initialization.

int x{}; is value initialization (since C++11),

This is the initialization performed when a variable is constructed with an empty initializer.

And the effects of value initialization in this case (i.e. neither class type nor array type) are:

4) otherwise, the object is zero-initialized.

Finally the effects of zero initialization in this case are:

If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T.

On the other hand, int x = 0; is copy initialization; x is initialized with the value 0.

As @PaulR mentioned, there's a difference that int x{}; is only supported from c++11, while int x = 0 has not such restriction.

like image 52
songyuanyao Avatar answered Oct 20 '22 08:10

songyuanyao


In this case they are identical. int x{} will initialise x in the same way as static int x would; i.e. to zero. That said, I find int x = 0 clearer and it has the benefit that it works with older C++ standards.

like image 31
Bathsheba Avatar answered Oct 20 '22 08:10

Bathsheba


There is difference: int x=1.888; will work with x as 1. Lot of trouble later.All professional guys have sometime faced , in their or others' code.

but int x{1.888}; will NOT compile and save trouble.

like image 41
Rathinavelu Muthaliar Avatar answered Oct 20 '22 10:10

Rathinavelu Muthaliar