-2

Even though the name of the string signifies address of the first element in the string,when I perform this:

char str[]="dog";
cout<<str<<endl;

How come the whole string gets printed?

kaylum
  • 13,833
  • 2
  • 22
  • 31
nrb
  • 5
  • 8
  • Why would one not allow for the other? You pass the start of the string to `cout` and it's implemented to read the string from that point. What mystery is there? If I give you just the location of the start of my street how come you are able to walk down the whole street? – kaylum Sep 15 '16 at 01:47
  • 3
    I'm voting to close this question as off-topic because it represents a failure to read the introductory textbook. – Joshua Sep 15 '16 at 01:48
  • 1
    I think that's a valid question, and as show Lee Daniel Crocker answer, it's non-trivial. –  Sep 15 '16 at 01:51

1 Answers1

4

In C++, the "<<" operator is "smart". It knows the types of the thing to its left and to its right, and if the thing to its right is a character pointer and the thing to its left is an output stream, it prints the string rather than the value of the pointer.

In C, you have to tell printf() which one to do with "%p" or "%s", but "<<" makes that choice for you.

Google "C++ operator overloading"

Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55