Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use curly braces({}) or equal sign(=) when initialize a variable [duplicate]

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:

variable initialization

But I see that there are more people use = than {}.
So which method is a good principle to persist? = or {}?

like image 448
Caesium Avatar asked Nov 27 '22 17:11

Caesium


1 Answers

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.

like image 53
Shades Avatar answered Dec 05 '22 11:12

Shades