5

Under the maxim constexpr everything and with the introduction of consteval in C++20, more and more code is evaluated at compile time.

This leads to the obvious question: How do we debug this?

The only hints, currently, are compiler errors. But what if the code compiles, but still does not do what is expected. Are there any tools that can help with this? Any inspection possibilities?

A related question is: How to know which ones will really be 'executed' at compile time and which remain runtime despite the qualifier.

non-user38741
  • 671
  • 5
  • 19
  • 3
    `constexpr` functions can be called in non constexpr context, to you can debug them as regular functions. – Jarod42 Aug 16 '20 at 11:19
  • @Jarod42: That doesn’t apply to `consteval`, which is tagged. Nor can you easily instrument your constexpr functions for debugging; while you can use `std::is_constant_evaluated`, that doesn’t help *reproducing* whatever usage in constant expressions. – Davis Herring Aug 16 '20 at 17:13
  • Stumbled upon this 2017 Herb Sutter talk: https://youtu.be/4AfRAVcThyA?t=1807 Bottom right it says: **C++17 => need compile-time debug**. A minute later he even lists **compile-time watch**. What has been done about it in the three years that passed since then? ;-) – non-user38741 Sep 15 '20 at 22:16

1 Answers1

4

I personaly use static_assert as a debuger for constexpr functions ,it is not the best tool but it can replace code like if (irational_value) cout<<"bug"; .A silly example to evaluate at compile time if the 6th fibonaci number is actually 13

#include <vector>
#include <iostream>

int main(){
    constexpr unsigned sixth_fib=[](){
        unsigned prev=1;
        unsigned sum=1;
        for (unsigned i=0;i<5;i++)
        {
            auto tmp=sum;
            sum+=prev;
            prev=tmp;

        }
        return sum;
    }();
    static_assert(sixth_fib==13);
    std::cout<<sixth_fib<<std::endl;

}
Spyros Mourelatos
  • 484
  • 1
  • 8
  • 19
  • In which universe is `static_assert` or `cout<<"bug"` called *debugging*??? – non-user38741 Sep 26 '20 at 15:13
  • 1
    Actually in this one ! [print debugging](https://stackoverflow.com/questions/189562/what-is-the-proper-name-for-doing-debugging-by-adding-print-statements) . I don't say it is a full debugging mechanism , but nothing is .Someone has to use various debugging methods for a big program to use this method is the most "on the fly" method that you can use everywhere but remember that chances are you will never have to do a stack trace or check for a memory leak in a `constexpr` context so no valgrind for `constexpr` .But indeed I believe it would be great to have gdb on `constexpr` context – Spyros Mourelatos Sep 30 '20 at 06:06