0

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;
        }
    }
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
musicmatze
  • 4,124
  • 7
  • 33
  • 48

1 Answers1

10

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 2
    I'd suggest you refrain from answering obvious duplicates in the future... โ€“  Oct 25 '13 at 20:12
  • 1
    @H2CO3- I'm sorry... I didn't realize this was a duplicate. I actually thought it was really interesting because in every C implementation I've ever seen I know that division is integer division, but I didn't know whether the C spec guaranteed this. I hoped that this answer would provide an authoritative reference beyond "it works on every compiler I've ever tried it on." โ€“ templatetypedef Oct 25 '13 at 20:26
  • 2
    Fair point. The standard guarantees this, but beware: such simple questions are *generally* already asked and answered, even multiple times. โ€“  Oct 25 '13 at 20:27