When I am reading The C++ Programming Language 4th Edition, to initialize a variable, the author said it's better to use {}
than =
to initialize a variable:
But I see that there are more people use =
than {}
.
So which method is a good principle to persist? =
or {}
?
Which one you choose depends on your own coding style and what you think is best. The most important thing is once you decide which method to use, use that method consistently. Don't switch between methods, it can make it very confusing to read your code. An additional style of variable initialization since C++98 (Called "direct initialization") is:
int variable(1)
But I would advise you against doing this, it doesn't work in certain circumstances, as your book may cover.
My personal style is the one my grandfather who worked on IBM mainframes in the 1960's taught me:
int
Variable1 = 2,
Variable2 = 39,
Variable3 = 45;
bool
Foo = true,
Bar = false;
// etc.
You'll notice I use the "=" sign over curly braces too. This seems to be how the majority of people write their code so me and my Grandfather write it that way to reduce confusion when people read our code. How accepted this method is in a corporate setting or in an organization I do not know, I simply thought it was the most attractive and intuitive style. It also saves a lot of typing.
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