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

3

18

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 {}?

Staffard answered 18/12, 2017 at 2:49 Comment(5)
Like Bjarne says, for the first 30 years the {} option wasn't available, so older code uses =. If you work with such old code, you should probably continue using = to be consistent. In new code you have the option to use {} instead, and with some new features it is required. So, consistency...Faience
Which ever one you use keep it the same and be able to read bothDotard
What can we tell you that the book did not?Midas
These are not equivalent. T x = y; is copy-initialization (even though no copying takes place), and will not work with explicit constructors.Dysphonia
Does this answer your question? Why is list initialization (using curly braces) better than the alternatives?Luxembourg
B
8

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.

Bursiform answered 18/12, 2017 at 3:5 Comment(3)
Initializing a variable as such does work in C++98. For all future readers, this method of initialization is called direct initialization.Scruff
it's not true. {} is different and is recommended for new code Why is list initialization (using curly braces) better than the alternatives?. int variable(1) has worked since the first C++ standard (C++98)Luxembourg
@Luxembourg Thanks! I wrote this a few years ago and didn't know it had worked in C++98 at the time, I think I got it confused with the X object{arg} initialization which (According to cppreference) seems to have been introduced in C++11. I edited the post to reflect this.Bursiform
B
-1

Before any other comes up with the silly idea that T a = b ( where b is type of T ) ends up in an assignment operator call,

Lets clear it, in C++ and in any object orient language, assignment operator can not be used on a not yet created object. This is initialization, and this was an invoke of copy constructor all the time, was not matter of C++ version.

In this case the '=' is just a syntactic sugar.

See the Reference in the Explanation section:

The copy constructor is called whenever an object is initialized (by direct-initialization or copy-initialization) from another object of the same type (unless overload resolution selects a better match or the call is elided), which includes initialization: T a = b; or T a(b);, where b is of type T;

Buster answered 18/2, 2021 at 7:0 Comment(0)
J
-4

One reason the book suggests using an initializer is that it becomes the initial value.

When using the assignment '=', in some cases you end up constructing the object which gives it an initial value and then the code uses the assignment operator of the class type to change the initial value, so it is less efficient. This is only in some cases, depending on the constructors available and so on.

However, in most cases modern compilers can optimize it to make it the same thing. So it's not worth worrying about.

One problem with C++ is there is always several ways to do the same thing, no matter how simple that thing may be.

Jaynes answered 18/12, 2017 at 3:9 Comment(10)
This is rarely the case anymore: en.cppreference.com/w/cpp/language/copy_elisionGadmann
Yes, you are right, which is why I said most modern compilers optimize it to the same thing.Jaynes
Let's face it, the reason there are so many ways to do the same thing is the history of the language.Jaynes
The question is about initialization syntax, not assignment vs. initialization.Fabio
I agree with juanchopanza. "the code uses the assignment operator" - no, it doesn't. This answer is just wrong, and that's worse than useless.Anacoluthia
@Anacoluthia Guess what this symbol is: = It's an operator. It has a name. It's called the "assignment operator". You can either use the default C++ behaviour for it or you give it your own behaviour each time you define a class. But that is what it is. en.cppreference.com/w/cpp/language/operators Why on earth is this site so full of people who think they are smarter than Einstein? This is unbelievable. You guys nitpick about the silliest little things because you all want to feel like the smartest earthlings in existence.Jaynes
@Anacoluthia You want to know what is worse than useless? People like you who spend their time lecturing other people for no reason, because it makes ya feel mighty and powerful. Now you're feeling the instinct to lecture me why you're right and the web site cppreference.com is wrong. Well, here's a suggestion: don't do it.Jaynes
@SeanF It depends on where = is being used - in certain cases, yes, it is an assignment operator (e.g. int a; a = 5;), in other cases, like this one, well.. It isn't. As per C++ standard, clause 11.6.15: "The initialization that occurs in the = form of a brace-or-equal-initializer, or <...> is called copy-initialization."Karinekariotta
@SeanF In addition: There's so much irony in the statement of "You want to know what is worse than useless? People like you who spend their time lecturing other people for no reason, because it makes ya feel mighty and powerful."Karinekariotta
The = here is not an assignment operator but one of several ways to invoke a constructor. Even if copy elision did not occur, that would invoke a copy or move constructor, not any assignment operator. Initialisation invokes one or more constructor, never any assignment operator. A class without an assignment operator can still be copy or move constructed with =. Vice versa, presence of an assignment operator does not matter if a class is not copyable or movable; the compiler won't fallback to default constructing and then assigning. The idea it will is wrong & an embarrassing hill to cling to.Muscolo

© 2022 - 2024 — McMap. All rights reserved.