Many a times I have seen the following statements:
char* ch = "Hello"
cout<<ch;
The output I get is "Hello". I know that ch points to the first character of the string "Hello" and that "Hello" is a string literal and stored in read only memory. Since, ch stores the address of the first character in the string literal, so shouldn't the statement,
cout<<ch;
give the output "the address of a character" because, it is a pointer variable? Instead it prints the string literal itself.
Moreover, if I write this,
ch++;
cout<<ch;
It gives the output, "ello". And similarly, it happens with more consecutive ch++ statements too.
can anybody tell me, why does it happen?
Btw, I have seen other questions related to string literals, but all of them address the issue of "Why can't we do something like *ch='a'?
EDIT : I also want to ask this in reference to C, it happens in C too, if I type,
printf("%s",ch);
Why?
Best Answer
There's overloaded version of
operator<<
This overload is called whenever you use something like:-
This overload defines how to print that string rather than print the address. However, if you want to print the address, you can use,
as this would call another overload which just prints the address to stream:-