I'm new to C++ (coming from C), and I found some strange behavior that I didn't expect.
The symbol &
gets you the location of a variable. This code
int a = 2;
std::cout << &a << "\n";
will output something like 0x7fffc010cb44
which makes sense, since this is where a
is stored.
But if the variable is a character:
char b = 'x';
std::cout << &b << "\n";
The output here is simply
x
What's more bizarre, is that if I add some completely unrelated variables to the program, and I output only the location of the first one
char b = 'x';
char c = 'y';
char e = 'z';
std::cout << &b << "\n";
The program outputs all of them!
xyz
This clearly has something to do with memory allocation, since the other variables have nothing to do with b
, but I have no idea why this happens.
So my question is - why does std::cout << &b << "\n";
print the character stored in b
instead of the memory location of b
?