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?
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?
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:
It outputs 65525Code:#include <stdio.h> #include <stdint.h> int main() { uint16_t a=4; a-=15; printf("%d\n",a); return 0; }
Last edited by cronus; 05-28-2020 at 08:22 PM.
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; }
Ordinary language is totally unsuited for expressing what physics really asserts.
Only mathematics can say as little as the physicist means to say. - Bertrand Russell