Your first example still falls under the rules of uniform initialization.
int x { 15 };
is uniform initialization, with a non-default value.
https://mbevin.wordpress.com/2012/11/16/uniform-initialization/
Your second example tells the compiler to use a default value, a value that depends on the type. With
int
that would be zero,
double
is
0.0
, etc.
If you are initializing a
POD (plain old data such as
int
) variable with uniform initialization and don't care about what that value is typing the value or letting the compiler select the default value is personal choice. I prefer to let the compiler decide.
You should do what makes it easier for you to read and understand the code.
One major advantage to uniform initialization is the compiler catches simple programming "boo-boos," such as initializing an
int
with a
double
value from a previously created variable or a function. The compiler warns about a type narrowing. If I really do want to assign a
double
to an
int
I do a
cast
so I know the conversion is deliberate.
https://www.learncpp.com/cpp-tutorial/explicit-type-conversion-casting-and-static-cast/
Using the assignment
operator= when initializing a variable is the old school way to do things.
int x = 15;
Trying to reassign a new value to an already created variable with uniform initialization won't work:
201 202 203 204 205
|
int x { };
// lots of code to do stuff
int x { 25 };
|
I know, I've accidentally tried more than once. ;)