Reputation: 3
So, I've recently learned that 'char*' is a synonym for 'string' and that is points to the first character of the string and also that you only need to know the address of the first character,and where the string ends to display its contents. But I'm confused as to how the pointer iterates through the string.
Basically, why and how does this code:
char *s="Hello";
cout<<s<<endl;
Output:"Hello"
and not: "H"
Upvotes: 0
Views: 39
Reputation: 596592
operator<<
is overloaded for char*
so it can iterate a null terminated string. It simply starts at the given character and then outputs in a loop until the null terminator is reached. For example, it does the equivalent of this:
ostream& operaror<<(ostream &os, const char *str)
{
while (*str != '\0') {
os << *str;
++str; // <-- moves to next character
}
return os;
}
Upvotes: 2