4 ms·
ptrdiff_t is a signed type - after all, the diff stands for difference, which implies that it could be negative. size_t is an unsigned type - it is used to rep
by nhaehnle 11y ago
ptrdiff_t is a signed type - after all, the diff stands for difference, which implies that it could be negative.
size_t is an unsigned type - it is used to represent the sizes of objects in memory, which can never be negative.
- 0x0 11y agoBut couldn't you just get along with unsigned types for both (i.e. just size_t)? I mean, two's complement means adding or subtracting is the same for unsigned and signed ints? Is it just for the convenience of being able to compare along the lines of (somePtrDiff < 0)? But then again you could just as well compare (somePtr > someOtherPtr)? Another funny thing I just discovered: You can't declare an array like "char somearray[SIZE_MAX]"; clang gives "error: array is too large (18446744073709551615 elements)". But you can use SIZE_MAX as an array index (although it gives a warning "array index -1 is past the end of the array"). Also, trying to declare an array like "char somearray[SIZE_MAX/8]" inside a simple main() just sends clang into 100% cpu...
- ben0x539 11y agoSometimes you actually want to do math beyond adding and ubstracting with ptrdiff_t. Multiply a potentially negative offset with something? Compare two offsets, one of them negative, with each other?
- 0x0 11y agoFor multiplication, I think the math works out the same for unsigned and signed, within mod bit-size and you throw away the "overflow"? I.e. (for 16bit pointers), 0xff_ff * 2 == 0x1_ff_fe (-1*2 == -2). For greater-than/smaller-than comparisons, I see the utility of working in the signed space though. I guess it all depends on expectations. If you have a pointer to the very last byte of a 2^32 address space (0xFFFF_FFFF), and subtract a pointer to the second byte from the start (0x0000_0001), you'll end up with a diff that should be "SIZE_MAX-2", but will be parsed as "-2" in the signed interpretation.
- mikeash 11y agoPointer subtraction is only valid for pointers within the same object. To overflow a signed ptrdiff_t, you'd need to allocate an array of char with more than 2^31 elements. This can be done on some systems, but it's really rare.
- ben0x539 11y ago> For multiplication, I think the math works out the same for unsigned and signed, within mod bit-size and you throw away the "overflow"? Yeah, true. I recalled there being separate instructions and then messed up my napkin math to check if it made a difference within the relevant range.