Home > Enterprise >  Int subtraction from a string
Int subtraction from a string

Time:05-24

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;
}

CodePudding user response:

It doesn't give an error because it's your job to make sure to honor array bounds. Like many other things this is impossible to always detect so it's left up to the user to not do it.

Compiler have gotten better at warning about it though:

<source>:4:36: warning: offset '-50' outside bounds of constant string [-Warray-bounds]
<source>:5:36: warning: array subscript 50 is outside array bounds of 'const char [14]' [-Warray-bounds]

Both under and overflow on a constant string get detected just fine by gcc and clang.

CodePudding user response:

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

  • Related