Why does constexpr not cause compilation to fail on index out of bounds

Viewed 72

I wrote a small helper function in my c++ project which should convert values of an enum to a predetermined list of strings. I wrote it like this:

#include <stdint.h>
#include <iostream>

enum things{
    val1 = 0,
    val2,
    val3,
    val4
};

constexpr const char* things_strings[4] = {"A", "B", "C", "D"}; 

constexpr const char* get_thing_string(const things thing){
    return things_strings[static_cast<uint32_t>(thing)];
}

int main(){
  std::cout << get_thing_string(things::val1);
  std::cout << get_thing_string(static_cast<things>(12));
}

I expected this to fail compilation. I thought that by using constexpr I can prevent index out of bounds issues during compile time. Is there a way to enforce this in C++ 11?

1 Answers

Yes, but you're calling the function at run time. If you call this function in a compile time context, e.g. by assigning to a constexpr variable, you'll get a compile time error:

constexpr auto c = get_thing_string(static_cast<things>(12));  // error

Here's a demo.


Note that in c++20, you can make the function consteval and then compilation will fail in all cases, since the function must be evaluated at compile time.

Here's a demo.

Related