Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cout and String concatenation

I was just reviewing my C++. I tried to do this:

#include <iostream>

using std::cout;
using std::endl;

void printStuff(int x);

int main() {
    printStuff(10);
    return 0;
}

void printStuff(int x) {
    cout << "My favorite number is " + x << endl;
}

The problem happens in the printStuff function. When I run it, the first 10 characters from "My favorite number is ", is omitted from the output. The output is "e number is ". The number does not even show up.

The way to fix this is to do

void printStuff(int x) {
    cout << "My favorite number is " << x << endl;
}

I am wondering what the computer/compiler is doing behind the scenes.

like image 722
UnseededAndroid Avatar asked Dec 18 '22 13:12

UnseededAndroid


2 Answers

The + overloaded operator in this case is not concatenating any string since x is an integer. The output is moved by rvalue times in this case. So the first 10 characters are not printed. Check this reference.

if you will write

cout << "My favorite number is " + std::to_string(x) << endl;

it will work

like image 160
Ajay Pal Avatar answered Jan 04 '23 15:01

Ajay Pal


It's simple pointer arithmetic. The string literal is an array or chars 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.

like image 21
Sami Kuhmonen Avatar answered Jan 04 '23 14:01

Sami Kuhmonen