在C中,是否保证1/2 == 0?

时间:2013-10-25 20:08:42

标签: c arrays math integer binary-search

在C中保证1/2 == 0?我需要它来实现二进制搜索:

/*
 * len is the array length
 * ary is an array of ptrs
 * f is a compare function
 * found is a ptr to the found element in the array
 * both i and offset are unsigned integers, used as indexes
 */

for(i = len/2; !found && i < len; i += offset) {
    res = f(c->ary[i]);

    if (res == 0) {
        found = c->ary[i];
    }
    else {
        offset = (res < 0 ? -1 : 1) * (i/2);
        if (!offset) {
            i = len+1;
        }
    }
}

1 个答案:

答案 0 :(得分:10)

是的,这是有保证的。根据C ISO规范,§6.5.5/ 5:

  

/运算符的结果是来自第一个操作数的除法的商   第二;

1/2的商为0,因此{C}中保证1 / 2 == 0为真。

希望这有帮助!