why can't set array size with a const int from argument from main()

Apr 24, 2013 at 2:13am
why i can't declare an array whose size is derived from a constant int argument from the main() function?

1
2
3
4
void test(const int x)
{
int arr[x];
}


And how can I make it?
Apr 24, 2013 at 2:18am
The constant needs to be known at compile time, your code is trying to dynamically create an array at run time.

The simplest (but crude) solution is to just give the array a fixed size which is generously large enough.

Alternatives include using new [] and delete []. Or less risky, use a vector instead.
Apr 24, 2013 at 2:18am
The array size has to be a constant expression, that is, expression, whose value is known at compile time.

You can use a vector:
1
2
3
4
void test(const int x)
{
    std::vector<int> arr(x);
}
Apr 24, 2013 at 2:44am
oic, thx alot :)
Apr 24, 2013 at 2:48am
another question, i'm a bit puzzled at what time exactly is the compile time? could you give me a little example? :)
Apr 24, 2013 at 2:52am
It means after you finish typing your code, you compile it (and maybe get some compiler error messages). Those are compile-time errors.

That is in contrast to run-time, which is what you get after the code has been compiled (turned into an executable program) and you try to run it.
Topic archived. No new replies allowed.