cout<<"ccccc"+2;
Output:
ccc
I tried searching for it online and I know it is a very dumb question but couldn't find anything anywhere. Please if someone could help me out.
cout<<"ccccc"+2;
Output:
ccc
I tried searching for it online and I know it is a very dumb question but couldn't find anything anywhere. Please if someone could help me out.
"ccccc"+2;
"ccccc"
decays to the const char *
pointer referencing the first character of the string literal "ccccc"
. When you add 2
to it, the result references the third element of the string literal.
It is the same as:
const char *cptr = "ccccc";
cptr += 2;
cout << cptr;
When you wrote:
cout<<"ccccc"+2;
The following things happen(to note here):
"ccccc"
is a string literal. In particular, it is of type const char[6]
.
Now, this string literal decays to a pointer to const char
which is nothing but const char*
due to type decay. Note that the decayed const char*
that we have now is pointing to the first character of the string literal.
Next, 2
is added to that decayed pointer's value. This means that now, after adding 2
, the const char*
is pointing to the third character of the string literal.
The suitable overloaded operator<<
is called using this const char*
. And since this const char*
is pointing to the third character of the string literal, you get the output you observe.