没有用括号确定操作符的优先级顺序,导致错误一例

168 阅读1分钟

代码如下:

int test1 =  getpid() << 8  + (plugID << 4);
int test2 = (getpid() << 8) + (plugID << 4);
 
DEBUG_FORMAT("getpid()=%d, plugID=%d, %d ? %d",
    getpid(), plugID,
    test1, test2);

  在吾理解中,test1应该是等于test2的。实际上呢?输出如下:

07-19 14:13:37.062 initSHM-15:getpid()=203488, plugID=1, -536870912 ? 52092944
07-19 14:13:37.231 initSHM-15:getpid()=203488, plugID=2,   52092928 ? 52092960

  从结果来判断,(这个编译器中)+的优先级高于<<,所以test1的实际优先级是:

int test1 =  getpid() (<< 8  + (plugID << 4));
int test2 = (getpid()  << 8) + (plugID << 4);

  test2才是我们期望的。所以,不要想当然,应该显式确定优先级。