user2269707
user2269707

Reputation:

How to debug if a constexpr function doesn't run on compile time?

For example I have a constexpr function, but I use a runtime variable (not marked as constexpr) to take the return value. In this case, I'm not sure whether the function runs on compile time or runtime, So is there any way to debug?

At first I thinked about static_assert, but it looks like static_assert cannot do this. Then I thought convert the code to assembly code, but it is way too difficult to check the assembly code to figure out.

Upvotes: 0

Views: 320

Answers (1)

Klaus
Klaus

Reputation: 25623

Before C++20 there is no way to directly handle it from the program itself.

With C++20 you have std::is_constant_evaluated.

If the return type from your constexpr func is a valid non type template parameter, you can force your function to be evaluated in compile time like this:

constexpr int func( int x ) 
{
    return x*2;
}

template < auto x > 
auto force_constexpr_evaluation()
{
    return x;
}

int main()
{
    int y = force_constexpr_evaluation<func(99)>();
}

If you are using c++20 already, you can directly force compile time evaluation by using consteval

Debugging on assembly level should be not so hard.

  • If you see a function call to your constexpr func, it is running in run time.
  • If you see directly the forwarded value, it was evaluated in compile time.
  • If it is inlined, you should be able to detect it by having the function name associated from the debug symbols to the location of the inlined code. Typically, if you set a breakpoint on the constexpr function and it is not always be executed at compile time but inlined, you get a number of breakpoints not only a single one. Even if it is one, it points to the inlined position in that case.

BTW: It is not possible to back port std::is_constant_evaluated to older compilers, as it needs some implementation magic.

Upvotes: 1

Related Questions