12

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
Caesium
  • 789
  • 3
  • 7
  • 24
  • 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... – Bo Persson Dec 18 '17 at 02:58
  • Which ever one you use keep it the same and be able to read both – Jake Freeman Dec 18 '17 at 03:01
  • 1
    What can we tell you that the book did not? – Galik Dec 18 '17 at 03:06
  • These are not equivalent. `T x = y;` is *copy-initialization* (even though no copying takes place), and will not work with explicit constructors. – rustyx Dec 18 '17 at 07:17
  • 1
    Does this answer your question? [Why is list initialization (using curly braces) better than the alternatives?](https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives) – phuclv Feb 18 '21 at 07:33

3 Answers3

9

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.

Shades
  • 667
  • 1
  • 7
  • 22
  • Initializing a variable as such does work in C++98. For all future readers, this method of initialization is called direct initialization. – FriskySaga Jan 15 '21 at 18:15
  • it's not true. `{}` is different and is recommended for new code [Why is list initialization (using curly braces) better than the alternatives?](https://stackoverflow.com/q/18222926/995714). `int variable(1)` has worked since the first C++ standard (C++98) – phuclv Feb 18 '21 at 07:04
  • @phuclv 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. – Shades Feb 21 '21 at 16:16
-3

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;

-5

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.

Sean F
  • 4,344
  • 16
  • 30
  • This is rarely the case anymore: http://en.cppreference.com/w/cpp/language/copy_elision – Fantastic Mr Fox Dec 18 '17 at 03:17
  • 1
    Yes, you are right, which is why I said most modern compilers optimize it to the same thing. – Sean F Dec 18 '17 at 03:19
  • Let's face it, the reason there are so many ways to do the same thing is the history of the language. – Sean F Dec 18 '17 at 03:25
  • 4
    The question is about initialization syntax, not assignment vs. initialization. – juanchopanza Dec 18 '17 at 05:26
  • 3
    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. – MSalters Dec 18 '17 at 10:18
  • @MSalters 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. – Sean F Dec 20 '17 at 02:32
  • @MSalters 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. – Sean F Dec 20 '17 at 02:36
  • 3
    @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._" – Algirdas Preidžius Dec 20 '17 at 10:12
  • 2
    @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._" – Algirdas Preidžius Dec 20 '17 at 12:18
  • 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. – underscore_d Aug 12 '20 at 15:36