0

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;   
}
einpoklum
  • 118,144
  • 57
  • 340
  • 684
Kaj Half
  • 9
  • 3
  • 1
    related: https://stackoverflow.com/questions/10869459/why-does-streaming-a-char-pointer-to-cout-not-print-an-address – NathanOliver Feb 04 '19 at 14:10
  • When you use the address-of operator `&` you get a pointer to the variable you get the address of. If the variable is of type `char` then the pointer to it will be of type `char *`. Which is the common type for null-terminated byte ***strings***. – Some programmer dude Feb 04 '19 at 14:11
  • Should be reopened. This question is not about why I don't see the address, it is about from where the extra characters came, and why them changes when you change the single character. – SHR Feb 04 '19 at 14:29

1 Answers1

2

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.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • 4
    Technically it's Undefined Behavior. You can't even rely on it printing the `'d'` itself; `std::cout` might very well crash on an access violation before it has constructed the string to print. – MSalters Feb 04 '19 at 14:14
  • Good point @MSalters, added to answer. – Paul Evans Feb 04 '19 at 14:36