0

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.

14
  • 5
    Signed integer overflow is undefined behavior. Compile-time evaluation doesn't do undefined behavior. Does the outcome change if you switch all your integers to unsigned? Commented Nov 1, 2023 at 17:44
  • 1
    If you want to be a bit more in control, use std::uint64_t instead of int Commented Nov 1, 2023 at 17:50
  • Also for consteval consider using const std::string_view instead of const char* (so you can avoid pointer arithmetic) Commented Nov 1, 2023 at 17:52
  • 1
    whats the error message? Commented Nov 1, 2023 at 17:52
  • 1
    Integer overflow is undefined behaviour. This means the program is legally allowed to format your hard drive, eat your lunch, and steal your girlfriend. If you want any of that to be "a part of the algorithm", go ahead and use an algorithm that can result in integer overflow. If not, use unsigned types. Unsigned arithmetic doesn't overflow, it wraps around. Commented Nov 1, 2023 at 17:58

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.