You should already know by now that the type of a variable defines the interval of values that it can store and the operations that the software can execute upon them. An int type can store, for instance, values ranging from -2,147,483,648 to 2,147,483,647. If you try to assign a value outside of this interval to an int, you will find yourself in what programmers call overflow exception.
An int variable stores 32 bits. The compiler uses the most significant bit to determine the sign of the variable, 0 being positive and 1 negative. Therefor, the program uses 31 bits to represent the value of the variable. To understand why the overflow exception occurs, you must have a look at the binary representation of the variable’s value. Lets consider the following values:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
0 0000 0000 0000 0000 0000 0000 0000 0000 1 0000 0000 0000 0000 0000 0000 0000 0001 2 0000 0000 0000 0000 0000 0000 0000 0010 3 0000 0000 0000 0000 0000 0000 0000 0011 4 0000 0000 0000 0000 0000 0000 0000 0100 //etc... 2147483645 0111 1111 1111 1111 1111 1111 1111 1101 2147483646 0111 1111 1111 1111 1111 1111 1111 1110 2147483647 0111 1111 1111 1111 1111 1111 1111 1111 -2147483648 1000 0000 0000 0000 0000 0000 0000 0000 |
You can test this by yourself, using the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelloWorld { class Program { static void Main(string[] args) { int positive = 2147483647; int negative = -2147483648; Console.WriteLine("{0} + 1 is {1}", positive, positive + 1); Console.WriteLine("{0} - 1 is {1}", negative, negative - 1); Console.Read(); } } } |
The result will be this:
Additional Information
So, we are printing a line on the console output, using a string of which you will learn later as being a variable that can store text. Inside it you can notice the {0} and {1} items, and after it, the negative and negative – 1 parameters. In this case, {0} will be replaced by the first parameter (negative) and {1} will be replaced by the second parameter (negative – 1). You can add as many items/parameters as you want, respecting the same principle As you can see, adding 1 to 2,147,483,647 will result in a negative number, while subtracting 1 from -2,147,483,647 will result in a positive value. One of the dangers of the overflow is that you might often not notice the error, because the C# compiler will not warn you about the overflow exception. In other words, the program keeps running, even if the overflow exception occurs. That is why you have to be careful when using large numbers, because overflow exceptions can be hard to track. The concepts explained in this lesson are also shown visually as part of the following video: