Search code examples
c++constexprstatic-assert

C++ - Static_assert and ability of constexpr functions to evaluate at runtime


I'm reading about constexpr and static_assert features in C++ and one thing seems confusing to me - I've read that constexpr functions are not necessarily always evaluated during compilation and they can sometimes evaluate at runtime. One thing that bothers me is that static_assert is always checked during compilation. So what happens, if we pass constexpr to static_assert, but compiler chooses to evaluate that constexpr during runtime? Is that even an issue?


Solution

  • constexpr functions are not necessarily always evaluated during compilation

    It is always evaluated at compile time when it should be, so when its return value is used as const expression.

    static_assert is one of this case. constexpr int value = f(); or C<f()> c;(template argument) are other cases.

    but in std::cout << f(), it is not required to be computed at compile time.

    And in void bar(int p) { const int v = f(p);}, f cannot be evaluated as constexpr (depend of parameter of function which are not (cannot be) constexpr).