int type exceeding values loop

There is an interesting fact about the Integer type in C# in the cases where its values exceed outside of the limits.
C# wraps around the int values and if you exceed the max value it starts from the min again. I will best illustrate this with the example below:

Lets use the 32 bit int type, which range is from -2147483648 to 2147483647. If you have the following code:

public static void Main()
{
	int n = int.MaxValue;	
	n += 1;
	Console.WriteLine(n);
}

What do you think will be printed on the console? Or maybe an exception will be thrown?

Actually it will print the following result:
-2147483648
It means the next after the max value is the min one. It starts over from the beginning and there is an endless loop.

It is good to know about that behavior when you are dealing with big number calculations and you should handle the mentioned scenario by yourself according to the business needs.

If you need to have an error on such exceeding cases, then it is possible to achieve it.
You can have an exception if you surround the code with the checked keyword:

checked
{
	int n = int.MaxValue;
        n += 1;
   	Console.WriteLine(n);
}

This produces the exception:

Run-time exception (line 10): Arithmetic operation resulted in an overflow.
Stack Trace:
[System.OverflowException: Arithmetic operation resulted in an overflow.] at Program.Main() :line 10

You can observe the same situation with long type as well.

One thought on “int type exceeding values loop

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