-7

I was asked this question in an interview and i had no clue at all:

Why the array-out-of-bounds exception has not been included in C++ even after so many updates?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Nakul Sharma
  • 419
  • 1
  • 4
  • 13
  • 2
    Did you read this: https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why – AntonH Mar 20 '17 at 18:36
  • 3
    Because Java does bounds checking, and C++ does not, at least not by default in the compilers I used back when I did C++. IIRC, some C++ compilers have an option to add bounds checking (and its associated overhead) to the compiled code. – T.J. Crowder Mar 20 '17 at 18:36
  • Exceptions are expensive. C++'s motto is don't use expensive stuff unless the user requests it. So if you want all that extra overhead you use a `std::vector`/`std::array` and it's `at` function which does do bounds checking and will throw an exception. – NathanOliver Mar 20 '17 at 18:44
  • The difference is that in C++ the bounds checking is called `v.at(i)` instead of `v[i]`. So you can choose if you want it or not. – Bo Persson Mar 20 '17 at 20:16

1 Answers1

2

Since you were asked this question in an interview, the interviewer was probably trying to gain some knowledge about your understanding of principles behind C++ design.

In this case, the principle the interviewer was looking to discuss is that in C++ you don't pay for things that you do not explicitly request. Although bounds checking can be ridiculously cheap in terms of CPU, it is not free. Implementing it at the language level would make you pay for what you did not request explicitly, thus violating one of C++ fundamental design principles.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523