- static uint32_t M_HashGen(const char* s)
- {
- const int32_t A_PRIME = 54059;
- const int32_t B_PRIME = 76963;
- const int32_t C_PRIME = 999983;
- int32_t myVar = 37;
- while (*s) {
- myVar = (myVar * A_PRIME) ^ (s[0] * B_PRIME);
- printf ("myVar: %d, abs(myVar): %d, s[0] = %c\n", myVar, abs(myVar));
- s++;
- }
- /* Since all ints are used in the above algorithm, ensure that a positive value
- is used as the input to the modulo operation */
- return (abs(myVar) % C_PRIME);
- }
myVar: 8388078, abs(myVar): 8388078
myVar: -1817466845, abs(myVar): -1817466845
myVar: 1228909722, abs(myVar): 1228909722
myVar: -929334365, abs(myVar): -929334365
myVar: -649350200, abs(myVar): -649350200
myVar: -457962121, abs(myVar): -457962121
myVar: -788115438, abs(myVar): -788115438
myVar: 1346474570, abs(myVar): 1346474570
myVar: -2032483059, abs(myVar): -2032483059
myVar: -149788679, abs(myVar): -149788679
As can be seen from the output, the abs() calls fail on negative numbers after the first integer overflow of myVar. However if the code above is changed to have myVar become static as shown below, all is well:
- static uint32_t M_HashGen(const char* s)
- {
- const int32_t A_PRIME = 54059;
- const int32_t B_PRIME = 76963;
- const int32_t C_PRIME = 999983;
- static int32_t myVar = 37;
- while (*s) {
- myVar = (myVar * A_PRIME) ^ (s[0] * B_PRIME);
- printf ("myVar: %d, abs(myVar): %d, s[0] = %c\n", myVar, abs(myVar));
- s++;
- }
- /* Since all ints are used in the above algorithm, ensure that a positive value
- is used as the input to the modulo operation */
- return (abs(myVar) % C_PRIME);
- }
myVar: 8388078, abs(myVar): 8388078
myVar: -1817466845, abs(myVar): 1817466845
myVar: 1228909722, abs(myVar): 1228909722
myVar: -929334365, abs(myVar): 929334365
myVar: -649350200, abs(myVar): 649350200
myVar: -457962121, abs(myVar): 457962121
myVar: -788115438, abs(myVar): 788115438
myVar: 1346474570, abs(myVar): 1346474570
myVar: -2032483059, abs(myVar): 2032483059
myVar: -149788679, abs(myVar): 149788679
As can be seen the abs() performs correctly as long as myVar is declared as static. Is this a bug with the compiler or do I need to use a compiler option to fix or am I completely missing something.
FYI: I can't replicate with VS 2022 running this function on a WInodws 11 PC or other microcontrollers (Infineon and STM32).
Any help would be greatly appreciated