+ 4
Weird
//adding int to a string/ const char * int main(){ cout<< 5+ "abcdefgh"; } /* this output: fgh if i change 5 to 4, it output: efgh why is this so and why it is possible to add them together */
4 ответов
+ 5
Rather try to put "5" instead of 5
+ 4
I suppose this is equivalent to
char arr[] = "ABCDEF";
char* ptr = arr;
cout << ptr + 3; //DEF
The string class has no overloaded operator+ for int. The string literal is interpreted as a pointer to an array of chars by the compiler. Now pointer arithmetic is legal C++, so the code compiled smoothly.
The reason why it prints the whole substring rather than a char only can be related to how the output stream prints (pointer to) array of chars different than array of other types.
+ 3
The same issue as
https://www.sololearn.com/Discuss/1058833/?ref=app
+ 3
Char * is a pointer and adding anything to pointer will increment the address of pointer to which it is pointing. Your string at creation will point to 1st letter 'a', "5 +" will increment it to point to 5th letter.