Why do C implicit conversions operate like they do?
Asked Answered
W

1

7

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!

Woken answered 15/7, 2012 at 8:31 Comment(2)
Perfect example of why you should compile with basically all possible warnings enabled. As to why that's in the standard though.... No idea :p. (Unless you mean specifically 1. That's just a 2's compliment overflow.)Radiant
Example of such warning message: warning: large integer implicitly truncated to unsigned typeRica
A
7

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.

Anecdotic answered 15/7, 2012 at 8:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.