logoalt Hacker News

throwaway894345yesterday at 8:03 PM2 repliesview on HN

That’s definitely not true. Unsigned ints have no “negativity” semantic. Wrapping around is what happens when you decrement the minimum value of any integer type, including signed types. Regardless of the type you use to represent an integer value that cannot legally be negative, you will have to take care not to allow your program to return values lower than zero for things like indices or sizes.


Replies

oasisaimlesslyyesterday at 8:33 PM

> Wrapping around is what happens when you decrement the minimum value of any integer type, including signed types.

No, signed wraparound is undefined behavior in C, whereas unsigneds are defined to wraparound. If you use -ftrapv, signed wraparound is an immediate abort().

show 2 replies
einpoklumyesterday at 10:33 PM

> Unsigned ints have no “negativity” semantic.

They do. The code:

    unsigned x;
    unsigned y = -x;
is well-defined in C and C++. See this discussion on StackOverflow for spec text and reference:

https://stackoverflow.com/q/8026694/1593077

show 1 reply