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?
There's overloaded version of operator<<
ostream& operator<< (ostream& , const char* );
This overload is called whenever you use something like:-
char *p = "Hello";
cout << p;
This overload defines how to print that string rather than print the address. However, if you want to print the address, you can use,
cout << (void*) p;
as this would call another overload which just prints the address to stream:-
ostream& operator<< (ostream& , void* );
Printing a char* in C++ gives you the string rather than a pointer because that's how the language is defined, and in turn because that's what makes sense and is useful. We rarely need to print the address of a string, after all. In terms of implementation, it can be achieved by overloading an operator:
std::ostream& operator <<(std::ostream&, const char*);
You may find something like that in your standard library implementation, but it will actually be a template:
template <typename CharT>
std::basic_ostream<CharT>& operator <<(std::basic_ostream<CharT>&, const CharT*);
And it will probably have even more template parameters.
As for why ch++ gives you a string starting from the second character, well, that's because incrementing a pointer advances it to the next element in the "array" it points to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With