"Hello World"
is not std::string
, it's a string literal so it's type is const char[]
. When adding an integer like you're doing with i
here you're actually creating a temporary const char*
that first points to the first element of the const char[]
which is 'H', then you move it 2 spots (because i
is 2) so it points to 'l', then you pass that pointer to cout
and thus cout
starts printing from 'l'. Doing binary operations on such types is called Pointer Arithmetic.
To get a better understanding using an example char
array, your code under the hood is similar to:
const char myHello[] = "Hello World";
const char* pointer = myHello; // make pointer point to the start of `myHello`
pointer += i; // move the pointer i spots
cout<< pointer <<endl; // let cout print out the "string" starting at the character pointed to by the new pointer.
Note that if you try to "move" the pointer too much so that it's pointing to something out of the string and then try to access this pointer you get Undefined Behaviour. Same as how accessing an array out of bounds is UB. Just make sure index < size
.