unable to define array size via function parameter

Apr 22, 2020 at 12:01am
hi, im trying to define the size of an array through a const function parameter, but it returns an error

1
2
3
4
5
  void example(const int len) {
      std::array<int, len> myarr;
  }

 example(1);


Error:

example.cpp:38:22: error: 'len' is not a constant expression
std::array<int, len> myarr;


example.cpp:38:22: note: in template argument for type 'unsigned int'
Last edited on Apr 22, 2020 at 12:03am
Apr 22, 2020 at 12:12am
There is a difference between a 'constant' and a 'constant expression'

A constant expression NEEDS to be known at compile time. So your code is invalid because it relies on a parameter len that is only determined at run time. Whenever you use a template, the compiler manually inserts the constant expression during compilation, therefore it needs to know what value the size of std::array is when it goes to insert it.

If it were like this:
1
2
const int len = 5;
std::array<int, len> myarr;


This would be valid, since len is now a constant expression known at compile time. Since C++11, we have the constexpr keyword that can be used exclusively for constant expressions and regular constants won't work, so this is equivalent:

1
2
3
4
5
constexpr int len = 5;
std::array<int, len> myarr; //Works

const int len2; //Is constant, but not a compile-time constant
constexpr int len3; //ERROR: Constexpr must have value at compile time! 
Apr 22, 2020 at 12:22am
...which is why I think std::array is all but useless.

For valanche’s benefit, in order to make his function work, it needs to be constexpr itself (which won’t work here), or to be templated:

1
2
3
4
5
6
7
8
9
10
11
template <int Length>
void example() {
  std::array<int,Length> myarray;
  ...
}

int main()
{
  example<12>();
  ...
}

Hope this helps.
Apr 22, 2020 at 12:55am
Function parameters are never constant expressions.
Apr 22, 2020 at 1:23am
As mbozzi said, function parameters are never constant expressions, but nontype template parameters ALWAYS must be constant expressions (with certain type restrictions)
Last edited on Apr 22, 2020 at 1:30am
Apr 22, 2020 at 4:26am
thank you so much guys, I learned a lot from you
Last edited on Apr 22, 2020 at 4:27am
Topic archived. No new replies allowed.