I have been just reading the book The C++ Programming Language by Bjarne Stroustrup. On the page 105, I tried the exercise 12 and I came to one (for me) crazy thing. After this, I managed to successfully solve the exercise, but I am interested, how and why does this happen? Here is the minimized code (only with this specific case):
int main()
{
char c;
std::cin >> c;
std::cout << "" + c;
}
Try to input one character and the result is pretty surprising. For 'a', I get Community\VC\Tools\MSVC\14.28.29910\include\vector, and for 'Z' I get o\2019\Community\VC\Tools\MSVC\14.28.29910\include\vector. This applies to other characters I try to input as well. I really can't find any pattern in this. What does the vector directory have to do with the inputed character?
I know that such adding string with character is forbidden (adding different entities) and there are many alternatives I used afterwards, but I am interested: Why does this actually happen? Where does the Visual Studio get some random directory, slice it, and serve it in the console?
As of comments, I now know that I actually added together the address of the string literal and the numerical value of the character. But now I am interested: why are the addresses of string literals always the same? Consider the following code:
int main()
{
char c;
std::cin >> c;
std::cout << "" + c << std::endl << &"" << std::endl << &"Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.28.29910/include/vector";
}
The addresses of the string literals "" and "Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.28.29910/include/vector" (the longest string I got) are always the same. Why? Isn't the memory address given randomly?