Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Use signed because pointer differences in C are signed:

    char *a, *b;
    size_t foo = a - b; /* generates a warning with -Wconversion */
This tells me that C's native integer type is ptrdiff_t, not size_t. (And I agree this is crazy: unsigned modular arithmetic would be fine, but they chose a signed result for pointer subtraction).

Why care about this? You should try to get a clean compile with -Wconversion, but also you should avoid adding casts all over the place (they hide potential problems). It's cleaner to wrap all instances of size_t with ptrdiff_t- you can even check for signed overflow in these cases if you are worried about it.

There is another reason: loop index code written to work properly for unsigned will work for signed, but the reverse is not true. This means you have to think about every loop if you intend to do some kind of global conversion to unsigned.



> (And I agree this is crazy: unsigned modular arithmetic would be fine, but they chose a signed result for pointer subtraction).

But. Signed means that i < j implies that p + i < p + j, or that p < q implies that p - r < q - r.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: