#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)
Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: