I understood that int x{};
is a kind of default-initialization, but is it exactly the same as writing int x = 0;
?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With