#57 – Overflow on Integer Operations

When executing arithmetic operations on integer-based types, an overflow can occur when the result of the operation cannot be stored in the destination type.

By default in C#.NET, when overflow occurs for integer-based types, the most significant bits of the result are discarded.  Effectively, this results in the value appearing to wrap.  E.g. Large values wrap to smaller (or large negative for unsigned) values.

Here are some examples of wrapping on integer-based overflow.

 uint u1 = 0xffffffff;
 u1 = u1 + 5;       // Now 0x00000004 (wrapped)

 int n1 = int.MaxValue;      // 2147483647 (0x7FFFFFFF)
 n1 = n1 + 1;                // Now -2147483648 (wrapped)

 short s1 = short.MinValue;
 s1 = (short)(s1 - 1);       // Now 32767 (wrapped)

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment