-5
#include <iostream>
using namespace std;

int main()
{
        cout<<"started "<<endl;
        int n= -2;
        int array[n];

        array[0]=100;
        array[1]=200;

        cout<<array[0]<<endl;
        cout<<array[1]<<endl;

        cout<<"over"<<endl;

        return 0;
}

Why does this compile and run? I expected a compilation error because value of n is negative.

jrok
  • 54,456
  • 9
  • 109
  • 141
Al-Alamin
  • 1,438
  • 2
  • 15
  • 34

1 Answers1

0

Variable-length arrays are not a C++ feature, so this line will cause a compilation error in a compiler that is ordered to strictly adhere to the C++ specification, regardless of the value of n (unless n is const and can be determined at compile-time):

int array[n];

Likely you are using a compiler that supports variable-length arrays as an extension. Therefore, the rules regarding what is valid depend entirely on the specific compiler and compiler options, and any code that you write using this extension will not be portable to compilers that don't support this non-standard feature.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • I am using latest version of CodeBlock with MinGW – Al-Alamin Oct 27 '14 at 20:11
  • 1
    @alalamin Then you are using g++, which does support VLAs. However, I would strongly recommend that you avoid using them because your code may not work on any other compiler. If you need an array whose size you don't know at compile-time then you should use `std::vector`. – cdhowie Oct 27 '14 at 20:12