0

Let's say that we have 2 code samples, A and B:
A.

int n;
cin>>n;
//n is read as 2483
//n never changes beyond this point
int a[n];
for(int i=0; i<n; i++)
cin>>a[i];

B.

int n;
cin>>n;
//n is read as 2483
//n never changes beyond this point
int a[10000];
for(int i=0; i<n; i++)
cin>>a[i];

Why is A "forbidden" by ISO, despite attempting to save memory based on the current needs, with B being preferred, even though it's wasting some memory (e.g. allocating memory for 10000 ints instead of the required, let's say, 2483 ints)?
Can someone please explain this to me, including the technical details?

John
  • 181
  • 9
  • 8
    (a) because the C++ Standard says (automatic and static storage duration) arrays of unknown size __at compile time__ are not allowed. (b) use `std::vector` – Richard Critten Nov 30 '19 at 16:58
  • You're not saving memory because the stack has a fixed size. – Sopel Nov 30 '19 at 17:08
  • why do you think changing n after the array declaration would make it any different? How else do you define 'not changed' at compile time than const? – Sopel Nov 30 '19 at 17:10
  • @RichardCritten I'm asking why doesn't the C++ standard allow it. More exactly, what technical details determined ISO to say that you should know the array size at compile time? – John Nov 30 '19 at 17:11
  • @Sopel Because I thought that the main concern is not to increase n after the array is declared, as it could make loops go outside the allocated memory, therefore creating undefined behaviour. – John Nov 30 '19 at 17:15
  • @John why the Standard doesn't allow it is usually off topic - answers might need to go back almost 40 years or there might even be no answer other than _"because"_ So questions of that type usually fall into the __Too Broad__ category of off-topic question. – Richard Critten Nov 30 '19 at 17:30
  • My guess would be that with variable length arrays it's easier to get into a problematic situation (due to limited stack space), and a more robust solution already exists - dynamically allocated memory (especially with std::vector). So there isn't really a compelling use case to support variable length arrays. – TheUndeadFish Nov 30 '19 at 17:54
  • @TheUndeadFish I did some reaearch in the meantime. Apparently, not having a constant array length doesn't allow you to declare it on the heap by using the `static` keyword. But if you don't use it, I don't think it provides any advantage. – John Nov 30 '19 at 18:10
  • Does this answer your question? [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – eesiraed Dec 01 '19 at 00:36

0 Answers0