News for hackers. Stuff that matters.
Re:About size_t and ptrdiff_t by 0x0 on Tuesday August 18, 2015 @01:26PM (#10080615)
But 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...

Re:About size_t and ptrdiff_t by ben0x539 on Tuesday August 18, 2015 @01:33PM (#10080696)
Sometimes 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?
Re:About size_t and ptrdiff_t by 0x0 on Tuesday August 18, 2015 @01:42PM (#10080775)
For 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.

Re:About size_t and ptrdiff_t by mikeash on Tuesday August 18, 2015 @02:13PM (#10081030)
Pointer 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.
Re:About size_t and ptrdiff_t by ben0x539 on Tuesday August 18, 2015 @04:49PM (#10082098)
> 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.