Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time debugging in C++

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.

like image 756
non-user38741 Avatar asked Oct 16 '22 01:10

non-user38741


1 Answers

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;

}
like image 123
Spyros Mourelatos Avatar answered Oct 18 '22 14:10

Spyros Mourelatos