-1

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;
}
Mudia
  • 13
  • 2
  • `"Hello, world"` is a string literal which decays to a pointer and then pointer arithmetic happens. – Jason May 24 '22 at 07:33
  • Because pointer/subscript arithmetic doesn't carry overhead of bounds checking. – The Dreams Wind May 24 '22 at 07:34
  • C++ doesn't have any bounds checking. It's your responsibility as a programmer to make sure there's no out-of-bounds errors in your code. – Some programmer dude May 24 '22 at 07:35
  • Why then adding 50 to a string gives an error and not a garbage values? – Mudia May 24 '22 at 07:37
  • 1
    Undefined behavior is, well, *undefined*. It can cause crashes, it can seemingly work, it can result in "garbage", or it can [summon nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). – Some programmer dude May 24 '22 at 07:39
  • As a side-note (and some shameless self-promotion), [negative indexes are valid](https://stackoverflow.com/questions/47170740/c-negative-array-index/47170794#47170794) and can sometimes be useful. – Some programmer dude May 24 '22 at 07:47
  • *Why doesn't the code below give an error that says the array is out of range?* Because C++ is not a nanny language, and expects the programmer to provide a valid program to the compiler. If the programmer provides an invalid program to the compiler, hilarity and hijinks ensue. Some lament that such a policy can incur an overabundance of bugs *job security*. – Eljay May 24 '22 at 12:37

2 Answers2

3

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

Jason
  • 36,170
  • 5
  • 26
  • 60
3

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.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42