Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "<<" or "+" to put strings together when using "cout"

Tags:

c++

console

cout

I have seen people output different strings together by using both "<<" and "+".

cout << firstname << lastname << endl;

versus:

cout << firstname + lastname << endl;

Is it better to use "<<" or does it not make much of a difference?

like image 861
iDrinkJELLY Avatar asked Jan 17 '13 22:01

iDrinkJELLY


People also ask

How do I add strings in cout?

The string literal is an array or char s and will be presented as a pointer. You add 10 to the pointer telling you want to output starting from the 11th character. There is no + operator that would convert a number into a string and concatenate it to a char array.

How do you concatenate strings in C++?

C++ has a built-in method to concatenate strings. The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function.

What is the operator used to combine strings together?

The ampersand symbol is the recommended concatenation operator. It is used to bind a number of string variables together, creating one string from two or more individual strings.


2 Answers

I would say its better to use << in that particular case. Otherwise, concatenation results in a temporary which could allocate memory for no good reason.

like image 93
K-ballo Avatar answered Sep 20 '22 12:09

K-ballo


Definitely, use << - concatenating the string will create a copy of the two strings pasted together. Whether it also allocates extra memory on top is a matter of how strings are implemented in the C++ library, but if the first and last names are "long enough" (bigger than 8-16 characters together), then it most likely WILL allocate memory (and then free it again when the temporary copy is no longer needed).

The << operator will have very little overhead in comparison, so no doubt it is better.

Of course, unless you do thousands of these things, it's unlikely that you will have a measurable difference. But it's good to not waste CPU cycles, you never know what good use they can be somewhere else... ;)

like image 27
Mats Petersson Avatar answered Sep 17 '22 12:09

Mats Petersson