Reputation: 491
When an integer number is out of the type's range, the max value + 1 is added / subtracted (depends on which part of the range the number was). For example,
unsigned short num = 65537;
num will have a value of 1 (65536 was subtracted). My question is: why does it happen? My intuition tells me it has something to do with the carry flag and the overflow flag, because the maximum value is always 1111....
Thanks in advance!
Upvotes: 7
Views: 166
Reputation: 263267
For a machine that uses two's-complement for signed integers the rules for conversion to an N-bit unsigned type are equivalent to discarding all but the low-order N bits. for typical hardware, this is the easiest way to do the conversion.
The standard permits other representations for signed integers, but uses the same conversion rules for the sake of consistency. This might require some extra work on such machines, but (a) such machines are quite rare, and (b) the expense should be fairly small anyway.
Upvotes: 7