4

I thought size of arrays should be constant.I code in VS 2019 and even when I do something like this:

    const int size = 5;
    int number[size];

I will receive this error expression must have a constant value ,only alternative for using an integer directly for array size ,is using macro define ,otherwise I will receive error.

But in some IDEs like dev ,it is even possible to took size of array as input from user.I also saw people code's here with user defined array size.

So here is my problem :

is it right ,to do this? are there risks and problem for user defined array size?

hanie
  • 1,863
  • 2
  • 7
  • 19
  • 1
    @Thomas I'm not sure, because I checked some of similar question like this ,but since they were about `c++` there answers is about `c++` too. – hanie Mar 21 '20 at 18:01
  • Sorry, didn't notice the `c` tag before. – Thomas Mar 21 '20 at 18:03
  • 1
    Search for VLA, Variable Lenght Arrays. They are allowed in C though recent revisiobs made the optional (=potentially unsupported). I'm pretty sure that this info is already covered by a question, but I cannot look for it right now. – Roberto Caboni Mar 21 '20 at 18:04
  • 1
    @RobertoCaboni it's all my fault not to search well ,but since most of questions I found with this topic were `c++` so I decided to ask it myself. – hanie Mar 21 '20 at 18:10

2 Answers2

4

Variable-length arrays (VLAs) are legal from C99 onwards, although some compilers like GCC will allow them as an extension in older versions too. From C11 onwards, compilers are no longer required to support VLAs and will define __STDC_NO_VLA__ as 1 if they don't support it.

VLAs are inherently risky: either you know the maximum size of your data beforehand, in which case you can allocate a fixed-length array, or you don't, in which case you run the risk of overflowing the stack.

It's worth noting that in C++, variable-length arrays were never part of the standard.

Thomas
  • 162,537
  • 44
  • 333
  • 446
-2

const has more the meaning "read-only" than constant. You can use an enumertaion. The members are treated as constants.

enum { size = 5 };
int number[size];

This should work.

MiCo
  • 391
  • 1
  • 6