0

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"; */ } 
2
  • 2
    Are you sure it's cin<<tt; instead of cin>>tt;? Commented Jun 27, 2013 at 13:19
  • Arrays must have a size that is known at compile time. Commented Jun 27, 2013 at 13:20

1 Answer 1

2

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. 
Sign up to request clarification or add additional context in comments.

2 Comments

In C++14 they're standard.
@Fanael: In C++14, both VLA's and dynarray (an alternative), are both options being considered, but I would refrain from saying "They're standard" until the standard actually comes out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.