<p>Suppose I have the following C code.</p>

<pre><code>unsigned int u = 1234;
int i = -5678;

unsigned int result = u + i;
</code></pre>

<p>What implicit conversions are going on here, and is this code safe for all values of <code>u</code> and <code>i</code>? (Safe, in the sense that even though <em>result</em> in this example will overflow to some huge positive number, I could cast it back to an <em>int</em> and get the real result.)</p>

[{'answer_id': 50632, 'author': 'Ozgur Ozcitak', 'author_id': 976, 'author_profile': 'https://Stackoverflow.com/users/976', 'pm_score': 9, 'selected': True, 'text': '<p><strong>Short Answer</strong></p>\n\n<p>Your <code>i</code> will be <em>converted</em> to an unsigned integer by adding <code>UINT_MAX + 1</code>, then the addition will be carried out with the unsigned values, resulting in a large <code>result</code> (depending on the values of <code>u</code> and <code>i</code>).</p>\n\n<p><strong>Long Answer</strong></p>\n\n<p>According to the C99 Standard:</p>\n\n<blockquote>\n  <p>6.3.1.8 Usual arithmetic conversions</p>\n  \n  <ol>\n  <li>If both operands have the same type, then no further conversion is needed.</li>\n  <li>Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.</li>\n  <li>Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.</li>\n  <li>Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.</li>\n  <li>Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.</li>\n  </ol>\n</blockquote>\n\n<p>In your case, we have one unsigned int (<code>u</code>) and signed int (<code>i</code>). Referring to (3) above, since both operands have the same rank, your <code>i</code> will need to be <em>converted</em> to an unsigned integer.</p>\n\n<blockquote>\n  <p>6.3.1.3 Signed and unsigned integers</p>\n  \n  <ol>\n  <li>When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.</li>\n  <li>Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.</li>\n  <li>Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.</li>\n  </ol>\n</blockquote>\n\n<p>Now we need to refer to (2) above. Your <code>i</code> will be converted to an unsigned value by adding <code>UINT_MAX + 1</code>. So the result will depend on how <code>UINT_MAX</code> is defined on your implementation. It will be large, but it will not overflow, because:</p>\n\n<blockquote>\n  <p>6.2.5 (9)</p>\n  \n  <p>A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.</p>\n</blockquote>\n\n<p><strong>Bonus: Arithmetic Conversion Semi-WTF</strong></p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void)\n{\n  unsigned int plus_one = 1;\n  int minus_one = -1;\n\n  if(plus_one &lt; minus_one)\n    printf("1 &lt; -1");\n  else\n    printf("boring");\n\n  return 0;\n}\n</code></pre>\n\n<p>You can use this link to try this online: <a href="http://codepad.org/yPhYCMFO" rel="noreferrer">https://repl.it/repls/QuickWhimsicalBytes</a></p>\n\n<p><strong>Bonus: Arithmetic Conversion Side Effect</strong></p>\n\n<p>Arithmetic conversion rules can be used to get the value of <code>UINT_MAX</code> by initializing an unsigned value to <code>-1</code>, ie:</p>\n\n<pre><code>unsigned int umax = -1; // umax set to UINT_MAX\n</code></pre>\n\n<p>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: <a href="https://stackoverflow.com/questions/809227/is-it-safe-to-use-1-to-set-all-bits-to-true">Is it safe to use -1 to set all bits to true?</a></p>\n'}, {'answer_id': 50648, 'author': 'Mats Fredriksson', 'author_id': 2973, 'author_profile': 'https://Stackoverflow.com/users/2973', 'pm_score': 2, 'selected': False, 'text': '<p>When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.</p>\n\n<p>So it is safe in the sense of that the result might be huge and wrong, but it will never crash.</p>\n'}, {'answer_id': 50653, 'author': 'Tim Ring', 'author_id': 3685, 'author_profile': 'https://Stackoverflow.com/users/3685', 'pm_score': 2, 'selected': False, 'text': '<p>When converting from signed to unsigned there are two possibilities. Numbers that were originally positive remain (or are interpreted as) the same value. Number that were originally negative will now be interpreted as larger positive numbers.</p>\n'}, {'answer_id': 50694, 'author': 'Taylor Price', 'author_id': 3805, 'author_profile': 'https://Stackoverflow.com/users/3805', 'pm_score': 1, 'selected': False, 'text': "<p>As was previously answered, you can cast back and forth between signed and unsigned without a problem. The border case for signed integers is -1  (0xFFFFFFFF). Try adding and subtracting from that and you'll find that you can cast back and have it be correct.</p>\n\n<p>However, if you are going to be casting back and forth, I would strongly advise naming your variables such that it is clear what type they are, eg:</p>\n\n<pre><code>int iValue, iResult;\nunsigned int uValue, uResult;\n</code></pre>\n\n<p>It is far too easy to get distracted by more important issues and forget which variable is what type if they are named without a hint. You don't want to cast to an unsigned and then use that as an array index.</p>\n"}, {'answer_id': 50879, 'author': 'smh', 'author_id': 1077, 'author_profile': 'https://Stackoverflow.com/users/1077', 'pm_score': 3, 'selected': False, 'text': '<p>Referring to <a href="https://rads.stackoverflow.com/amzn/click/com/0131103628" rel="nofollow noreferrer" rel="nofollow noreferrer">The C Programming Language, Second Edition</a> (ISBN 0131103628),</p>\n<ul>\n<li>Your addition operation causes the int to be converted to an unsigned int.</li>\n<li>Assuming two\'s complement representation and equally sized types, the bit pattern does not change.</li>\n<li>Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)</li>\n<li>The rules are a little more complicated in the case of combining signed and unsigned of differing sizes.</li>\n</ul>\n'}, {'answer_id': 832772, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': "<p>Conversion from signed to unsigned does <strong>not</strong> necessarily just copy or reinterpret the representation of the signed value.  Quoting the C standard (C99 6.3.1.3):</p>\n\n<blockquote>\n  <p>When a value with integer type is converted to another integer type other than _Bool, if\n  the value can be represented by the new type, it is unchanged.</p>\n  \n  <p>Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or\n  subtracting one more than the maximum value that can be represented in the new type\n  until the value is in the range of the new type.</p>\n  \n  <p>Otherwise, the new type is signed and the value cannot be represented in it; either the\n  result is implementation-defined or an implementation-defined signal is raised.</p>\n</blockquote>\n\n<p>For the two's complement representation that's nearly universal these days, the rules do correspond to reinterpreting the bits.  But for other representations (sign-and-magnitude or ones' complement), the C implementation must still arrange for the same result, which means that the conversion can't just copy the bits.  For example, (unsigned)-1 == UINT_MAX, regardless of the representation.</p>\n\n<p>In general, conversions in C are defined to operate on values, not on representations.</p>\n\n<p>To answer the original question:</p>\n\n<pre><code>unsigned int u = 1234;\nint i = -5678;\n\nunsigned int result = u + i;\n</code></pre>\n\n<p>The value of i is converted to unsigned int, yielding <code>UINT_MAX + 1 - 5678</code>.  This value is then added to the unsigned value 1234, yielding <code>UINT_MAX + 1 - 4444</code>.</p>\n\n<p>(Unlike unsigned overflow, signed overflow invokes undefined behavior.  Wraparound is common, but is not guaranteed by the C standard -- and compiler optimizations can wreak havoc on code that makes unwarranted assumptions.)</p>\n"}, {'answer_id': 3202886, 'author': 'Elite Mx', 'author_id': 259439, 'author_profile': 'https://Stackoverflow.com/users/259439', 'pm_score': -1, 'selected': False, 'text': "<p><strong>Horrible Answers Galore</strong></p>\n\n<p><em>Ozgur Ozcitak</em></p>\n\n<blockquote>\n  <p>When you cast from signed to unsigned\n  (and vice versa) the internal\n  representation of the number does not\n  change. What changes is how the\n  compiler interprets the sign bit.</p>\n</blockquote>\n\n<p>This is completely wrong.</p>\n\n<p><em>Mats Fredriksson</em></p>\n\n<blockquote>\n  <p>When one unsigned and one signed\n  variable are added (or any binary\n  operation) both are implicitly\n  converted to unsigned, which would in\n  this case result in a huge result.</p>\n</blockquote>\n\n<p>This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.</p>\n\n<p><em>smh</em></p>\n\n<blockquote>\n  <p>Your addition operation causes the int\n  to be converted to an unsigned int.</p>\n</blockquote>\n\n<p>Wrong. Maybe it does and maybe it doesn't.</p>\n\n<blockquote>\n  <p>Conversion from unsigned int to signed\n  int is implementation dependent. (But\n  it probably works the way you expect\n  on most platforms these days.)</p>\n</blockquote>\n\n<p>Wrong. It is either undefined behavior if it causes overflow or the value is preserved.</p>\n\n<p><em>Anonymous</em></p>\n\n<blockquote>\n  <p>The value of i is converted to\n  unsigned int ...</p>\n</blockquote>\n\n<p>Wrong. Depends on the precision of an int relative to an unsigned int.</p>\n\n<p><em>Taylor Price</em></p>\n\n<blockquote>\n  <p>As was previously answered, you can\n  cast back and forth between signed and\n  unsigned without a problem.</p>\n</blockquote>\n\n<p>Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.</p>\n\n<p><strong>Now I can finally answer the question.</strong></p>\n\n<p>Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 <strong>[1]</strong>. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.</p>\n\n<p>Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.</p>\n\n<p><strong>What is precision?</strong></p>\n\n<p>Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.</p>\n\n<p>[Gotchas]</p>\n\n<p>The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.</p>\n\n<p><strong>[1]</strong> The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.</p>\n"}, {'answer_id': 35253263, 'author': 'plugwash', 'author_id': 5083516, 'author_profile': 'https://Stackoverflow.com/users/5083516', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>What implicit conversions are going on here, </p>\n</blockquote>\n\n<p>i will be converted to an unsigned integer.</p>\n\n<blockquote>\n  <p>and is this code safe for all values of u and i?</p>\n</blockquote>\n\n<p>Safe in the sense of being well-defined yes (see <a href="https://stackoverflow.com/a/50632/5083516">https://stackoverflow.com/a/50632/5083516</a> ). </p>\n\n<p>The rules are written in typically hard to read standards-speak but essentially whatever representation was used in the signed integer the unsigned integer will contain a 2\'s complement representation of the number. </p>\n\n<p>Addition, subtraction and multiplication will work correctly on these numbers resulting in another unsigned integer containing a twos complement number representing the "real result". </p>\n\n<p>division and casting to larger unsigned integer types will have well-defined results but those results will not be 2\'s complement representations of the "real result".</p>\n\n<blockquote>\n  <p>(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.)</p>\n</blockquote>\n\n<p>While conversions from signed to unsigned are defined by the standard the reverse is implementation-defined both gcc and msvc define the conversion such that you will get the "real result" when converting a 2\'s complement number stored in an unsigned integer back to a signed integer. I expect you will only find any other behaviour on obscure systems that don\'t use 2\'s complement for signed integers.</p>\n\n<p><a href="https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation" rel="nofollow noreferrer">https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation</a>\n<a href="https://msdn.microsoft.com/en-us/library/0eex498h.aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/0eex498h.aspx</a></p>\n'}]
['https://Stackoverflow.com/questions/50605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4828/']