0

Integer + String in C++

If I write cout<<1 + "hello" in C++, The output is "ello". Why does this happen? Shouldn't it show an error as integers and strings can't be added?

30th Mar 2020, 7:13 PM
Ram Keswani
Ram Keswani - avatar
1 Resposta
+ 5
"hello" is not really a string in C++, it's a const char*. ( Well, actually it's a const char (&) [6] for correctness, but let's ignore that for now ) In other words, it's just a pointer to somewhere in memory. What you are really doing is adding 1 to that pointer. "hello\0" ^ Adding 1 to the pointer would make it point to the next character: "hello\0" ^ (hopefully it formats correctly, but it's pointing to the 'e' in case it doesn't, 'h' in the previous one) If you used an actual std::string object instead of the C style string, then this wouldn't be allowed.
30th Mar 2020, 8:09 PM
Dennis
Dennis - avatar