移位运算符优先级很低

 1 int main()
 2 {
 3     const char* str = "one";
 4     int hashValue = 0;
 5     while (*str != '\0')
 6     {
 7         hashValue = hashValue << 4 + *str;
 8         ++str;
 9     }
10 
11     return 0;
12 }

hashvalue的值一直为0,何解?

因为 左移 运算符的优先级很低,所以上面的表达式结果时这样的:

1 hashValue = hashValue << (4 + *str);

正确姿势:

1 hashValue = (hashValue << 4) + *str;

 

posted @ 2019-09-27 15:44  机智的小小帅  阅读(504)  评论(0编辑  收藏  举报