Agnel Kurian
Agnel Kurian

Reputation: 59456

When can you use a const int as the size of an array?

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
}

Upvotes: 3

Views: 2159

Answers (5)

W.F.
W.F.

Reputation: 13988

Since C++11 though you can use constexpr which would do what you expect. The constexpr says compiler that apart the variable is const its value can be evaluated at compile time.

Upvotes: 0

ANjaNA
ANjaNA

Reputation: 1426

  1. Array size should be known at compile time.
  2. const mean the value doesn't change.

So, this is about value of 'dim` at compile time.

In first case, it is unknown. compiler don't know the value of dim at compile time. It depends on the value passed to the function.

void f1(const int dim){
  int nums[dim];  // line 2: errors
}

In this case, dim value is known at compile time, so no issues.

void f2(){
  const int dim = 5;
  int nums[dim];  // ok
}

You can use a feature in c++ 11 for this.

define your function as constexpr.

constexpr int getDim(......)
{
    .......
    .......
    return dim;
}

then call getDim inside f1.

void f1(){
  int dim = getDim(...); //// computed at compile time
  int nums[dim];
}

Note that, use of constexpr depend on your application. Further refer this.

Upvotes: 1

Jarod42
Jarod42

Reputation: 217065

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.

Upvotes: 8

Ospho
Ospho

Reputation: 2796

Your understanding of the const keyword is wrong. const implies that within a certain contextual scope the variable will not change, not that the variable is determined at compile time.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409136

In f2 the constant dim is known at compile time, in f1 it's not.

And since C++ doesn't have variable-length arrays the dimensions of an array must be known at compile time.

The use of const for function arguments is more of a hint to the compiler that the function will not modify the argument, allowing the compiler to for example make optimizations based on that information.

Upvotes: 2

Related Questions