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

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?
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.
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);
}
oic, thx alot :)
another question, i'm a bit puzzled at what time exactly is the compile time? could you give me a little example? :)
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.