Home > Net >  Can someone please explain this output?
Can someone please explain this output?

Time:01-31

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.

CodePudding user response:

"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;

CodePudding user response:

When you wrote:

cout<<"ccccc" 2;

The following are the things that happen(to note here):

  1. "ccccc" is a string literal. In particular, it is of type const char[6].

  2. 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.

  3. Next, 2 is added to that decayed pointer's value. This means that now, after adding 2, the const char* is now pointing to the third character of the string literal.

  4. The suitable overloaded operator<< is called using the const char*.

  •  Tags:  
  • Related