1

I have been programming c++ for a while now. My question might still be naive though. :)

What is the difference between += and +. For e.g.

std::string a = "Hi";
a += "b" + "c";

OR

std::string a = "Hi";
a = a + "b" + "c";

If there is any difference, which one is more optimized to use? Which one have less operations count?

Hemant Bhargava
  • 3,251
  • 4
  • 24
  • 45
  • compiler should handle optimization – Kenny Ostrom Nov 07 '19 at 04:30
  • 1
    I believe the original C used a different assembly instruction for += which was more optimized. Now it doesn't make a lot of difference; the compiler will optimize it for you. –  Nov 07 '19 at 04:32
  • 2
    Mind you because there is no `string` involved in `a += "b" + "c";`'s addition of `"b" + "c"` the compiler'll probably get upset. – user4581301 Nov 07 '19 at 04:32
  • 1
    duplicate? https://stackoverflow.com/questions/34465848/operator-in-c – Santosh Dhanawade Nov 07 '19 at 04:33
  • @Satarakar I'd say yes, except user4581301 might have a point about std::string: It might be slightly different. Otherwise, yes, it's a dupe. –  Nov 07 '19 at 04:35
  • Looks like in the trivial case of `int`s there can be a subtle difference. How much it costs is something I'd have to profile. – user4581301 Nov 07 '19 at 04:49

1 Answers1

9

In this specific example, there's a big difference: a += "b" + "c"; doesn't compile, while a = a + "b" + "c"; does. The former attempts to add two pointers, which is syntactically invalid. The latter adds a std::string and a char* pointer, and there happens to be a suitable operator+ overload for that.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85