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

mus*_*tze 0 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

tem*_*def 10

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

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

1/2的商为0,因此1 / 2 == 0在C中保证为真.

希望这可以帮助!

  • 我建议你以后不要回答明显的重复...... (2认同)
  • 有道理.标准保证了这一点,但要注意:这些简单的问题*通常*已经被问及答案,甚至多次. (2认同)