For a char d, I get strange output when executing cout << &d

158 Views Asked by At

i just started to learn c++, and I don't really understand, why when I cout &d, it shows up the char d as many times as i have showed it up already + add 1 time. So it shows 3 time the char "d" here... for the line
cout << &d << endl;

if someone can explain me why, with simple word, i would thanks him. And i'm sorry if the question is stupid.

#include <iostream>
using namespace std;

int main() 
{

char d('d');

cout << d << endl;
cout << d << endl;
cout << &d << endl;


    return 0;   
}
1

There are 1 best solutions below

2
Paul Evans On

That's because & (in this context) is the address-of operator.

EDIT: As pointed out by @MSalters the C++ standard has this as Undefined Behavior, so anything can happen, but most current compilers will do the following:

So you're effectively passing a pointer to char to cout.operator<<(). This is treated as a C-style string and will print everything at that memory address up to the next \0 nul char. Your 'd' is put there by your char initialization. The rest is pretty much randomly what's in memory after it.