3 ms·
A diff can be negative, whereas a size can't. However, my inclination was to ask the opposite: doesn't ptrdiff_t need to actually be larger than size_t if it m
by hamburglar 11y ago
A diff can be negative, whereas a size can't. However, my inclination was to ask the opposite: doesn't ptrdiff_t need to actually be larger than size_t if it must hold signed values and still cover the entire size_t range of inputs?
- phkahler 11y ago>> doesn't ptrdiff_t need to actually be larger than size_t if it must hold signed values and still cover the entire size_t range of inputs? Yes, but if you're just storing the delta between two pointers and then adding/subtracting this diff to get from one to the other it will still work. Of course it will also work using size_t.
- hamburglar 11y ago>> if you're just storing the delta between two pointers and then adding/subtracting this diff to get from one to the other This would require keeping track of which one is bigger somewhere else unless you had enough room to store a sign. Seems like a pretty goofy way to go about it if you're going to the trouble of making a type specifically to hold a delta.
- aCthrowa 11y agoYes, this limits the utility of ptrdiff_t. But I don't believe you're allowed to subtract arbitrary pointers in C anyway. So you might need a >63-bit char array in order to legally hit this limit, and you probably don't have 263 of RAM. Practically, amd64 is already limited to more like 48 bits (4 levels of 9 bit pagetables describing 12 bit pages) of memory.
- 0x0 11y agoI guess it could happen for applications targeting win32 with the /3GB switch
- phkahler 11y ago>> This would require keeping track of which one is bigger somewhere else unless you had enough room to store a sign. Nope. You assume the math is being done mod 2^32 or 2^64 and it just works weather you use signed or unsigned integers. Pro-tip: the hardware does the exact same bit operations for signed and unsigned addition and subtraction (except for carry/borrow which aren't part of the C standard anyway). integer overflow is undefined, but this behavior is AFAICT universal anyway. If it didn't behave this way then a difference would in fact need the extra bit.
- hamburglar 11y agoOh, excellent observation. I am wrong. :)