Search code examples
c++stringpointer-arithmetic

Difference between ("hello" + 1) VS (*"hello") + 1 VS (*("hello" + 1))


Ive been giving the following assignment to explain what is happening in 3 statements but i can't figure it out.

cout << ("hello" + 1);    // ello
cout << (*"hello") + 1;   // 105
cout << (*("hello" + 1)); // e
  1. Why is number 2 a number instead of a character?
  2. does first one still have zero character? (to end string)

Solution

    1. *"hello" gives the first character of the string, 'h', of type char, with ASCII value 104. The integer promotion rules means that, when adding char and int, the char is converted to int, giving a result of type int. Outputting an int gives the numeric value.

    2. Yes. The string literal is an array ending with a zero character. Adding one to its address gives a pointer to the second character of the array; the remainder of the array is unchanged, so still contains the zero at the end.