+ 4

Why cout << "hi" + 5 gives this strange output?

Try cout << "hi" + 5; Output: ;L Is compiler angry on me? :(

10th Feb 2020, 4:48 PM
Alexik
Alexik - avatar
9 Respostas
+ 8
A string sits in a place in memory, from point start to point end, and by + you go to the next letter, like Seb TheS showed. When you try to access a letter beyond your string, you may get a random value. Often that's just what was at that point in memory before your program required this for its execution. That's popularly called 'garbage value'. (And you should not do this, since it's uncontrollable.) for funsies, run this: https://code.sololearn.com/cJqUS9OtOz82/?ref=app
10th Feb 2020, 5:18 PM
HonFu
HonFu - avatar
+ 5
When you add an integer to string it evaluate the string which is cut by the given amount of characters from the beginning: "hello" + 1 ---> "ello" "hello" + 2 ---> "llo" "hello" + 3 ---> "lo" But I've no idea what happened with: "hi" + 5
10th Feb 2020, 5:05 PM
Seb TheS
Seb TheS - avatar
+ 4
Are you really supposed to get an output like this?
10th Feb 2020, 4:51 PM
NightFox
NightFox - avatar
+ 1
HonFu, yes, fun) I know about all of this but forgot i can get elements of str this way and that's strange that the ;L is every time in the same place. In you example they are different every time.
10th Feb 2020, 5:42 PM
Alexik
Alexik - avatar
+ 1
Alexik, there's just no way to foresee this, it might depend on the hardware, the operating system, what programs you ran before or whatever. Calling it 'random' would be wrong, but it is arbitrary.
12th Feb 2020, 1:19 AM
HonFu
HonFu - avatar
0
I get ;L on any string + int in cout cout << "guuf" + 5 gives same ;L
10th Feb 2020, 5:13 PM
Alexik
Alexik - avatar
0
Alexik I got "uf" from "guuf" + 2.
10th Feb 2020, 5:15 PM
Seb TheS
Seb TheS - avatar
0
Try + 5
10th Feb 2020, 5:17 PM
Alexik
Alexik - avatar
0
Seb TheS. I got: when you out of range it gives this - ;L in cout and gives empty when assigned
10th Feb 2020, 5:18 PM
Alexik
Alexik - avatar