Suppose I have the following C code.
unsigned int u = 1234; int i = -5678; unsigned int result = u + i;
What implicit conversions are going on here, and is this code safe for all values of u and i? (Safe, in the sense that even though result in this example will overflow to some huge positive number, I could cast it back to an int and get the real result.)
Short Answer
Your
iwill be converted to an unsigned integer by addingUINT_MAX + 1, then the addition will be carried out with the unsigned values, resulting in a largeresult(depending on the values ofuandi).Long Answer
According to the C99 Standard:
In your case, we have one unsigned int (
u) and signed int (i). Referring to (3) above, since both operands have the same rank, youriwill need to be converted to an unsigned integer.Now we need to refer to (2) above. Your
iwill be converted to an unsigned value by addingUINT_MAX + 1. So the result will depend on howUINT_MAXis defined on your implementation. It will be large, but it will not overflow, because:Bonus: Arithmetic Conversion Semi-WTF
You can use this link to try this online: https://repl.it/repls/QuickWhimsicalBytes
Bonus: Arithmetic Conversion Side Effect
Arithmetic conversion rules can be used to get the value of
UINT_MAXby initializing an unsigned value to-1, ie:This is guaranteed to be portable regardless of the signed number representation of the system because of the conversion rules described above. See this SO question for more information: Is it safe to use -1 to set all bits to true?