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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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… 😉