News for hackers. Stuff that matters.
Re:Summary of C/C++ integer rules by adrian_b on Friday April 02, 2021 @01:39PM (#26673730)
While I also like to use unsigned numbers when that is the correct type of a variable, the C language does not really have support for unsigned integers.

As someone else already said, the so called "unsigned" integers in C are in fact remainders modulo 2^N, not unsigned integers.

While the sum and the product of 2 unsigned integers is also an unsigned integer, the difference of 2 unsigned integers is a signed integer.

The best behavior for a programming language would be to define correctly the type of the difference of 2 unsigned integers and the second best behavior would be to specify that the type of the result is unsigned, but to insert automatically checks for out-of-domain results, to detect the negative results.

As C does not implement any of these behaviors, whenever using unsigned integers you must either not use subtraction or always check for negative results, unless it is possible to always guarantee that negative results cannot happen.

This is a source of frequent errors in C when unsigned integers are used.

The remainders modulo 2^N can be very useful, so an ideal programming language would support signed integers, unsigned integers and modular numbers.

There are no comments on this comment yet.