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. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With