Why am I able to use a locally declared const int
as the size of an array declaration but am not allowed to do the same with a const int
passed as an argument?
For example, in the below code why do I get compiler errors only on line 2?
void f1(const int dim){
int nums[dim]; // line 2: errors
}
void f2(){
const int dim = 5;
int nums[dim]; // ok
}
Array size should be known at compile time.
const int
with local variables may do not work neither if the value is not known at compile time as:
void f2(){
const int dim = bar();
int nums[dim]; // error
}
In Both case, const int
tells that the value doesn't change, not that is it known at compile time.