+ 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 */

13th Oct 2018, 3:04 AM
Juan Sebastian
Juan Sebastian - avatar
4 ответов
+ 5
Rather try to put "5" instead of 5
13th Oct 2018, 5:41 PM
#DARK_PROGRAMMER_✔
#DARK_PROGRAMMER_✔ - avatar
+ 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.
13th Oct 2018, 4:34 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
13th Oct 2018, 5:53 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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.
13th Oct 2018, 5:40 PM
#DARK_PROGRAMMER_✔
#DARK_PROGRAMMER_✔ - avatar