1. ## unsigned int rollover?

If I am decrementing an unsigned int (16 bits) by a value say

k -=15;

what happens the next time around if k is sitting at a 4? Seems it would roll over to 65524....Is this correct? Can I keep handling it as an unsigned int?

2. Standard seems to define unsigned overflow to work as if modulo 1 + the largest value possible for that type. Signed overflow however is undefined behavior.

I believe the value should be 65525 though.

edit: yes, see below:

Code:
```#include <stdio.h>
#include <stdint.h>

int main() {
uint16_t a=4; a-=15;
printf("%d\n",a);
return 0;
}```
It outputs 65525

3. Originally Posted by ridgerunnersjw
If I am decrementing an unsigned int (16 bits) by a value say

k -=15;

what happens the next time around if k is sitting at a 4? Seems it would roll over to 65524....Is this correct? Can I keep handling it as an unsigned int?
It's undefined behaviour. Best thing to do is check before the subtraction.

4. 65525, actually, but yes, wraparound is well-defined with unsigned values.
Code:
```#include <stdio.h>
#include <stdint.h>

int main()
{
uint16_t n = (uint16_t)(-1); // -1 interpreted as unsigned gives largest value
printf("%u\n", (unsigned)n); // prints 65535

n = 4;
n -= 15;
printf("%u\n", (unsigned)n);      // prints 65525

// The bit pattern can be interpreted as a signed value and gives the
// correct signed answer due to 2's-complement representation.
printf("%d\n", (int)(int16_t)n);  // prints -11

return 0;
}```

5. Originally Posted by john.c
65525, actually, but yes, wraparound is well-defined with unsigned values.
Ah, right! It's only UB with signed values...