'Int subtraction from a string
Why doesn't the code below give an error that says the array is out of range?
#include <iostream>
int main() {
std::cout << "Hello, world!" - 50;
return 0;
}
Solution 1:[1]
Why the code below does not give the error that array is out of range?
Because "Hello, world!" is a string literal of type const char[14]that decays to a pointer(const char*) due to type decay.
Thus effectively, you're subtracting 50 from that resulting(decayed) pointer. And when operator<< dereferences this pointer, it will lead to undefined behavior.
Note that undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
