Problem with consteval and multiplying magic numbers. c++

114 views Asked by At

Alright, so I'm trying to make a function that will hash a string.

consteval int hash_string(const char* str)
{
    constexpr int magic_number = 13371337;
    
    int num1 = 1337;
    int num2 = 7331;
    
    //do stuffz here//
    
    return num1 + num2 * magic_number; //error
    return num1 + num2;                //okay :D
}

I'm assuming that it's due to an integer overflow and that the compiler is unable to solve for it. But it's part of the algorithm, I don't care about that.

I'm expecting that consteval will solve the function because it's all compile time stuff.

1

There are 1 answers

0
Nicol Bolas On BEST ANSWER

But it's part of the algorithm, I don't care about that.

But you should care about it, because C++ doesn't allow it. Signed integer overflow is undefined behavior. And during constant evaluation, if you provoke undefined behavior, your program is ill-formed.

Hence the compile error.

If your algorithm relies on something whose results are not defined, your algorithm needs to be changed.