In C, is it guaranteed that 1/2 == 0? [duplicate]

旧时模样 提交于 2019-12-02 21:56:21

问题


Is it guaranteed in C that 1/2 == 0? I need that for an implementation of binary search:

/*
 * 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:


Yes, this is guaranteed. According to the C ISO spec, §6.5.5/5:

The result of the / operator is the quotient from the division of the first operand by the second;

The quotient of 1 / 2 is 0, so 1 / 2 == 0 is guaranteed to be true in C.

Hope this helps!



来源:https://stackoverflow.com/questions/19598608/in-c-is-it-guaranteed-that-1-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!