0

Can you help me explain the result from the following code.

cout<< "Hello" + 1<< endl;

Why result came out as "ello", I know to print out Hello1 then I should use: cout<< "hello" << 1<< endl; But Can anyone help me explain the sequence of the above code: Thank you so much.

  • 5
    `"Hello"` is a pointer to an array of 6 `char`s (not quite, but close enough). Adding `1` to this pointer produces a pointer to the next `char`, namely `e`. That pointer is then interpreted as pointing to a NUL-terminated string `"ello"` – Igor Tandetnik Jun 01 '17 at 04:15

1 Answers1

4

Your example is roughly equivalent to this:

// `p` points to the first character 'H' in an array of 6 characters
// {'H', 'e', 'l', 'l', 'o', '\0'} forming the string literal.
const char* p = "Hello";
// `q` holds the result of advancing `p` by one element.
// That is, it points to character 'e' in the same array.
const char* q = p + 1;
// The sequence of characters, starting with that pointed by `q`
// and ending with NUL character, is sent to the standard output.
// That would be "ello"
std::cout << q << std::endl;
Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • Thank you so much Igor for your explanation, How can I accept the answer? I could not see Accept button around here. – Hien Nguyen Jun 01 '17 at 05:56