1
    const int size = arraySize();
    int list[size];

I get the following error:

expression must have a constant value

I know this may not be the best way to do it but it is for an assignment.

1
  • 2
    What is the definition of arraySize? If it can be constexpr then it'll work. Commented May 25, 2020 at 22:34

2 Answers 2

2

You should know that in C++ there are no dynamically allocated arrays.

Also, const variables are not necessarily known at compile time!

You can do one of the following:

  1. Declare the function arraySize as constexpr, assuming you can calculate its value at compile time, or create a constant (again, with constexpr) which represents the array size.
  2. Use dynamically allocated objects, such as std::vector (which is an "array" that can expand), or pointers. However, note that when you are using pointers, you must allocate its memory by using new, and deallocate using delete, which is error prone. Thus, I suggest using std::vector.

Using the first one, we get:

constexpr std::size_t get_array_size()
{
    return 5;
}

int main()
{
    constexpr std::size_t size = get_array_size();
    int list[size];
}

which compiles perfectly.

Another thing which is nice to know is that there is std::array which adds some more functionality to the plain constant-size array.

Sign up to request clarification or add additional context in comments.

Comments

1

Try dynamic allocation of this array.

 int size = arraySize();
 int* list;
 list = new int [size];

It should work. In addition, there is a condensed explanation of how dynamic arrays works: DynamicMemory

PS. Remember to free memory that you dynamically allocated, when it won't be needed:

delete [] list;

3 Comments

I am not sure this is the answer Omar was looking for. Since he seems to want to use his function arraySize()?
This code still use arraySize() function, because size is equal to return of arraySize().
Should use delete[] instead of delete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.