Ayush Pant
Ayush Pant

Reputation: 119

Dynamic allocation of array

Why the below code compilation success though dynamic allocation of array is not possible in C++? on uncommenting the comments it shows error??

#include<iostream>
#include <string>
using namespace std;
int main()
{
    string aa;
    cin>>aa;
    int a[aa.size()];// though allocating the array dynamically the compilation succeeded
    cout<<"COMPILATION SUCCESS"<<endl;

    /*char *p;
    cin>>p;
    int y=sizeof(p);
    int b[y];
    cout<<"COMPILATION ERROR"<<endl;
    */


    /*
    int tt;
    cin>>tt;
    int c[tt];//  shows error
    cout<<"ERROR";
    */
}

Upvotes: 0

Views: 186

Answers (1)

user529758
user529758

Reputation:

Because you appear to be using a compiler which allows this. VLAs in C++ are a GNU extension, any chance you are compiling this with g++ or clang++?

Set your compiler to strict ISO C++ mode, and it will warn you or error out.

What I get from clang++:

h2co3-macbook:~ h2co3$ clang++ -o quirk quirk.cpp -Wall -std=c++11 -pedantic
quirk.cpp:6:9: warning: variable length arrays are a C99 feature [-pedantic,-Wvla]
    char cs[s.size() + 1];
           ^
quirk.cpp:6:7: warning: unused variable 'cs' [-Wunused-variable]
    char cs[s.size() + 1];
         ^
2 warnings generated.

Upvotes: 2

Related Questions