2

I'm trying to create a constant function that takes in a size int as a template parameter and returns an array that size with each index filled with its respective power of 2.

 template <int sz>
consteval int* conflagtab() {
    int ar[sz] = {};
    for (unsigned int i = 0; i < sz - 1; i++) {
        ar[i] = conflag(i);
    }
    return ar;
}

However when I am trying to use it I get the error:

call to consteval function "conflagtab<sz>() [with sz=31]" did not produce a valid constant expression.

I tried putting it in global namespace to see if that had a change but it had no difference. I'm expecting it to just return a pointer to the array.

6
  • 2
    You return a dangling pointer. Commented Jun 27, 2024 at 9:08
  • I see, how do I make it so the pointer stays? Commented Jun 27, 2024 at 9:10
  • 1
    Unrelated: Your for loop leaves the last element untouched (maybe it's intended) Commented Jun 27, 2024 at 9:14
  • 1
    You could return std::array by value. Or you could accept a pointer to the array as a parameter, and fill the existing array with powers of two. Commented Jun 27, 2024 at 9:18
  • 1
    how is the title related to the question or error message? "invalid use of interpreter storage" isnt mentioned elsewhere Commented Jun 27, 2024 at 9:32

1 Answer 1

6

You can't return a raw array from a consteval function, especially by pointer. Your example, if it were not consteval, would be a dangling pointer. Finishing the constant evaluation and keeping a value that new[] created is not permitted, you have to delete[] somewhere later.

You can return a std::array:

template <int sz>
consteval std::array<int, sz> conflagtab() {
    std::array<int, sz> ar;
    for (unsigned int i = 0; i < sz - 1; i++) {
        ar[i] = conflag(i);
    }
    return ar;
}
Sign up to request clarification or add additional context in comments.

Comments

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.