0

I am trying to initialize an enum using the hash codes of the type label:

enum ValueType {
    CLOSED = hashCode("CLOSED"),
    OPEN = hashCode("OPEN"),
    SEKIHAIRITSU = hashCode("SEKIHAIRITSU"),
    ZWEITMANDAT = hashCode("ZWEITMANDAT")
};

ValueType valuetype;

The hashCode function is an implementation of Java's function:

constexpr long hashCode(const char *string) {
    long h = 0;
    int off = 0;

    for (int i = 0; i < strlen(string); i++) {
        h = 31 * h + string[off++];
    }

    return h;
}

I get an error on Sekihairitsu and Zweitmandat:

expression must have a constant value -- value exceeds range of "long"

The weird thing is, it isn't outside of long. When I run the hashCode function by myself, it returns -1606024481 for Sekihairitsu and -710079088 for Zweitmandat. Neither of those are outside the range of long, or even int.

Anybody know what the problem is? I have already tried enum ValueType : long.

KingWither
  • 29
  • 4
  • 6
    You have integer overflow. Ask yourself how are you getting negative numbers when everything you are working with is a positive number. – NathanOliver May 24 '21 at 16:53
  • On my platform, `std::strlen` is not `constexpr`. (Not sure if it is supposed to be, and my compiler isn't compliant.) – Eljay May 24 '21 at 17:13
  • @NathanOliver I know that, but why? I ran the function by itself and it works, no integer overflow. What in the initialization of an enum would cause an Integer overflow? – KingWither May 24 '21 at 17:26
  • Signed integer overflow is undefined behaviour, but you can always use an unsigned type like this [test here](https://gcc.godbolt.org/z/4fb7rhsYK) – MatG May 24 '21 at 17:41
  • @MatG Thanks, I made it even easier. Just change `constexpr long` to `constexpr unsigned long`, change `h` the same way, and it works! – KingWither May 24 '21 at 17:56
  • Shouldn't you use unsigned long? – Alessandro L. Feb 21 '23 at 08:04

0 Answers0