0

Ok so here's the code:

#include <iostream>

using namespace std;

int main()
{
    int size = 10;
    int array[size] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    array[10] = 10, array[11] = 11; // Setting values higher than the array
    
    cout << array[10] << endl << array[11] << endl;
}

My question is simply why can I set array[10] & array[11] when we can't set value to an array greater than it's size?

Shouldn't C++ NOT support dynamic array's? I know I'm misunderstanding something.

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
Daniel
  • 103
  • 1
  • 9
  • That code doesn't even compile. –  May 07 '21 at 02:21
  • I tried and it did. – Daniel May 07 '21 at 02:22
  • What compiler are you using? `size` should be a `static const int` for that to properly compile. And when that code is run, it throws an exception. –  May 07 '21 at 02:22
  • 4
    the code uses VLA which are not supported in C++. Some compilers (e.g. gcc, clang) support this as an extension, but you should not use VLA. MSVC for instance doesn't. – bolov May 07 '21 at 02:23
  • [This](https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why) link helped a lot, I got my answer. – Daniel May 07 '21 at 02:27
  • @404TeamNotFound It is enough for `size` to be `const` (but `constexpr` would be better semantically). It does not need to be `static`. – JaMiT May 07 '21 at 02:56

0 Answers0