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?
Here,
"someLetter: "is a string literal, i.e. aconst char *pointer, usually pointing to a read-only area of memory where all the string literals are stored.someLetteris achar, so"someLetter: " + someLetterperforms pointer arithmetic and adds the value ofsomeLetterto 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::clearmethod. This is completely arbitrary though, the pointer might end up pointing to another (possibly inaccessible) location, depending on the value ofsomeLetterand the content of the string literal storage area. In summary, this behavior is undefined, you cannot rely on it.