Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the + operator do in cout?

Tags:

c++

iostream

In the following code I got confused and added a + where it should be <<

#include <iostream>
#include "Ship.h"

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    char someLetter = aLetter(true);
    cout <<"Still good"<<endl;
    cout << "someLetter: " + someLetter << endl;
    return 0;
}

Should be

cout << "someLetter: " << someLetter << endl;

The incorrect code outputted:

Hello world!
Still good
os::clear

What I don't understand is why the compiler didn't catch any errors and what does os::clear mean? Also why wasn't "someLetter: " at the start of the line?

like image 876
Celeritas Avatar asked Dec 06 '22 14:12

Celeritas


1 Answers

Here, "someLetter: " is a string literal, i.e. a const char * pointer, usually pointing to a read-only area of memory where all the string literals are stored.

someLetter is a char, so "someLetter: " + someLetter performs pointer arithmetic and adds the value of someLetter to the address stored in the pointer. The end result is a pointer that points somewhere past the string literal you intended to print.

In your case, it seems the pointer ends up in the symbol table and pointing to the second character of the name of the ios::clear method. This is completely arbitrary though, the pointer might end up pointing to another (possibly inaccessible) location, depending on the value of someLetter and the content of the string literal storage area. In summary, this behavior is undefined, you cannot rely on it.

like image 68
Frédéric Hamidi Avatar answered Dec 09 '22 13:12

Frédéric Hamidi