Question about C behavior for unsigned integer downstream

In many places, I read that unsigned integer overflows are clearly defined in C, as opposed to signed ones.

Is the same not enough?

For example:

unsigned int x = -1; // Does x == UINT_MAX? 

Thank.

I cannot remember where, but I read somewhere that the arithmetic of unsigned integer types is modular, so if that were the case, then -1 == UINT_MAX mod (UINT_MAX + 1).

+18
c types integer integer-overflow underflow
May 03 '10 at 19:05
source share
3 answers

ยง6.2.5, clause 9:

A computation involving unsigned operands can never be overflowed, because a result that cannot be represented by an unsigned integer type is equal in magnitude to a reduced number, which is one greater than the largest value that can be represented by the result type.

Edit:

Sorry, the link is incorrect, but the result is still pinned. The correct reference is ยง6.3.1.3 (conversion of integers without signatures and without sign):

if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type as long as the value is in the range of the new type.

So yes, x == UINT_MAX .

+23
May 3 '10 at 7:22 pm
source share

-1, when it is expressed as 2 complement numbers, is 0xFF ... F for how many bits of your number. In unsigned space, this value is the maximum possible value (i.e., all bits are set). So yes, x == UINT_MAX. The following code emits "1" in the strict C99 compiler:

 #include <stdio.h> #include <stdint.h> #include <limits.h> int main(int argc, char **argv){ uint32_t x = -1; printf("%d", x == UINT_MAX ? 1 : 0); return 0; } 
+4
May 03 '10 at 19:07
source share

You mix signed and unsigned numbers that are uncool.

 unsigned int x = 0u - 1u; // is OK though 
-3
May 03, '10 at 19:20
source share



All Articles