Hemant Bhargava
Hemant Bhargava

Reputation: 3585

Difference between assignments operator (+= and =)

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?

Upvotes: 1

Views: 126

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52611

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.

Upvotes: 9

Related Questions