Is there a difference between int x{}; and int x = 0;?
They are both the exact same thing. They will both be initialized to 0
.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int y{};
int x = 0;
cout << "y: " << y << endl;
cout << "x: " << x << endl;
return 0;
}
OUTPUT:
y: 0
x: 0
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.
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.
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.