#include <stdint.h>
#include <utility>
#include <stdio.h>
#include <stdlib.h>
int calc_hash(signed char *s)
{
static const int N = 100003;
int ret = 1;
while (*s)
{
ret = (ret * 131 + *s);
++ s;
//printf("step %d\n", ret);
}
ret = (ret % N);
if (ret < 0) { ret += N;} //注意这句
if ((volatile int&)ret < 0) printf("error when ret(%d) < 0\n", ret);
if ((volatile int&)ret < 0) { ret += N;} //注意这句
return ret;
}
int main()
{
signed char buff[] = {124,57,32,38,7, 0};
printf("%d\n", calc_hash(buff));
return 0;
}
无论MSVC还是clang的最高优化都不会出错,只有gcc O2或O3都会出错(即打印出error when……),对于gcc,应使用-fwrapv防止gcc犯傻。