3 ms·
> I think C doesn't guarantee that 'size_t' is at least as large as a 'signed int' That doesn't matter, because size_t is large enough to hold any array index
by a1369209993 4y ago
> I think C doesn't guarantee that 'size_t' is at least as large as a 'signed int'
That doesn't matter, because size_t is large enough to hold any array index (that's kind of[0] the defining property of size_t), so any array index in a signed int can be safely converted to size_t. The real problem is that (using 16-bit size_t for illustrative purposes) if you have, say, x = (size_t)40000 and y = (size_t)50000 into a 60000-element array, x+y = (size_t)90000 = (size_t)24464, which means (x+y)/2 = 12232, which is the completely wrong array element.
0: Technically, size_t is large enough to hold any object size, but array elements can't be smaller than char (sizeof can't be less than 1), so a array can't have more elements than it's sizeof.
- deleted 4y ago[deleted]
- wizeman 4y ago> > I think C doesn't guarantee that 'size_t' is at least as large as a 'signed int' > That doesn't matter, because size_t is large enough to hold any array index (that's kind of[0] the defining property of size_t), so any array index in a signed int can be safely converted to size_t. Well, the Go code we're discussing has nothing to do with arrays or array indices, so `size_t` doesn't help here. Go look at the code :) It's a generic function for doing binary search, which accepts an `int` as a function argument, specifying the search size. The code is then doing: h := int(uint(i+j) >> 1) // avoid overflow when computing h Replacing the Go expression `uint(i+j)` with `(size_t)i+(size_t)j` in C like morelisp proposed would not work correctly if `size_t` is smaller than `int`. That's the point I was making.