Why can function pointers be `constexpr`?

At compile time, the compiler doesn’t know the address of sqrt. However, you cannot do anything at compile time with a constexpr function pointer that would allow you to access that pointer’s address. Therefore, a function pointer at compile time can be treated as an opaque value.

And since you can’t change a constexpr variable after it has been initialized, every constexpr function pointer can be boiled down to the location of a specific function.

If you did something like this:

using fptr = float(*)(float);

constexpr fptr get_func(int x)
{
  return x == 3 ? &sqrtf : &sinf;
}

constexpr fptr ptr = get_func(12);

The compiler can detect exactly which function get_func will return for any particular compile time value. So get_func(12) reduces down to &sinf. So whatever &sinf would compile to is exactly what get_func(12) would compile to.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)