What does the + operator do in cout?

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; } 

Must be

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

Incorrect code:

Hello World!
Still good
OS :: clear

I don’t understand why the compiler did not notice any errors and what does os :: clear mean? Also, why wasn’t "someLetter:" at the beginning of the line?

+4
source share
5 answers

Here "someLetter: " is a string literal, that is, a const char * pointer, usually pointing to a read-only region in memory where all 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 behind the string literal that you planned to print.

In your case, it seems that the pointer falls into the character table and points to the second character of the ios::clear method name. This is completely arbitrary, although the pointer may eventually point to a different (possibly inaccessible) location, depending on the value of someLetter and the contents of the literal storage area. So this behavior is undefined, you cannot rely on it.

+8
source

The + operator has nothing to do with cout .

As you can see from the this table, + has a higher priority than << , so the line of code violation is analyzed as follows:

 (cout << ("someLetter: " + someLetter)) << endl; 

In other words, + is applied to the char and char pointer. A char is an integral data type, so you really do pointer arithmetic by adding the integer char value on the right side to the pointer on the left, creating a new char pointer.

+3
source

I think the C string "someLetter: " uses char someLetter as an index and therefore points to some memory. Consequently, behavior.

In C ++, if you do stupid things, you get strange behavior. Tongue gives you a lot of rope to hang yourself.

+2
source

The + parameter executes an arithmetic pointer to "someLetter: " .

+2
source

You must remember that a literal string is just pointers to a certain area of ​​memory. What "someLetter: " + someLetter does, adds a value to this pointer, and then tries to print it.

0
source

Source: https://habr.com/ru/post/1413125/


All Articles