0

According to the C++ standard the size of an array must be greater than zero and a compile time constant and If the array is a VLA then it must have automatic storage duration, i.e. the array must be made local. In other words:

#include<iostream>
int size = 10; 
constexpr int Size = 10;
int ar[size]; /* error as size is not a compile time constant and ar does not have auto storage class. */
int Ar[Size]; // fine, no error as Size is a compile time constant.
int main()
{
    int arr[size]; // fine as arr has auto storage class.
    return 0;
}

So, my question is - why can’t we have a VLA in C++ with static storage duration?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 9
    C++ does not have VLA. There are compiler-specific extensions which allow C-style VLA, but they are non-standard. You should specifiy which compiler and which C++ version you use. – hyde Dec 25 '16 at 18:12
  • 3
    *why can’t we have a VLA in C++ with static storage duration* -- There are no VLA's in C++. Use `std::vector`. – PaulMcKenzie Dec 25 '16 at 18:15
  • @hyde Compiled it in Code::Blocks IDE with g++ as compiler(follows ISO C++11 standard). – Sourabh Khandelwal Dec 25 '16 at 18:19
  • 2
    @SourabhKhandelwal -- Change the compiler switches to `-Wall -pedantic`, and you will get a different result. – PaulMcKenzie Dec 25 '16 at 18:22
  • If you really want to use VLA with g++ (I'd recommend against it, stack allocation has relatively small size limits in addition to VLA being non-standard), see C++ section here: https://gcc.gnu.org/onlinedocs/gcc/Standards.html – hyde Dec 25 '16 at 18:28

1 Answers1

1

So, my question is - why can’t we have a VLA in C++ with static storage duration?

First of all VLA's aren't a standard c++ feature.

Well, if you have a compiler supporting VLA's, these cannot be applied for static storage allocation, since it's merely a runtime feature and all static storage allocation is done at compile time.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • So you mean local storage allocation happens at compile time? Also the compiler I'm using is g++ in code::blocks IDE. Don't if its Code::Blocks' own extension to support VLA. – Sourabh Khandelwal Dec 25 '16 at 18:22
  • @SourabhKhandelwal No, for VLA's it happens at runtime. Read my answer again please. – πάντα ῥεῖ Dec 25 '16 at 18:23
  • Thank you. I was scrolling down through my old questions and that is when I stumbled upon this. At the time of your answering this question, I did not quite get it, which I do now. Possibly because I have worked more with C++. So here is your answer getting accepted. Thanks again anyway. – Sourabh Khandelwal Jul 15 '18 at 15:53