Integers and integer overflow
The integer types
C# has eight integer types, and the difference is the number of bits and the sign. The four a program meets first are these:
| Type | Bytes | Range |
|---|---|---|
| byte | 1 | 0 to 255 |
| short | 2 | -32 768 to 32 767 |
| int | 4 | -2 147 483 648 to 2 147 483 647 |
| long | 8 | -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807 |
A literal without a suffix is an int if it fits, and a long if it does not; the suffix L asks for a long either way. sbyte, ushort, uint and ulong are the unsigned counterparts, and nint and nuint follow the width of the machine.
Ranges and the wrap-around
Every type has a MinValue and a MaxValue, and an arithmetic result that leaves the range wraps around instead of failing:
Console.WriteLine($"int: {int.MinValue} to {int.MaxValue}");
Console.WriteLine($"long: {long.MinValue} to {long.MaxValue}");
Console.WriteLine($"byte: 0 to {byte.MaxValue}");
int max = int.MaxValue;
Console.WriteLine($"max + 1: {max + 1}");
dotnet run
int: -2147483648 to 2147483647
long: -9223372036854775808 to 9223372036854775807
byte: 0 to 255
max + 1: -2147483648
The last line is the surprise: one more than the largest int is the smallest one, silently. The same happens at the other end and to every integer type. In a program that counts money, finds an index or multiplies two sizes, that silent wrap is a bug, and it is the reason a long or a decimal is the right type for a total that may grow.
An overflow the compiler catches
When both operands are constants, the compiler computes the result itself, and then it refuses:
int tooBig = int.MaxValue + 1;
Console.WriteLine(tooBig);
dotnet build
Program.cs(1,14): error CS0220: The operation overflows at compile time in checked mode
Build FAILED.
Program.cs(1,14): error CS0220: The operation overflows at compile time in checked mode
0 Warning(s)
1 Error(s)
The message names the reason: a constant expression is evaluated in checked mode by default. The wrap of the program above happened at run time, on a variable, and that is the case the compiler cannot see.
checked and unchecked
A checked block asks for the check at run time: an overflow throws OverflowException instead of wrapping.
try
{
checked
{
int max = int.MaxValue;
Console.WriteLine(max + 1);
}
}
catch (OverflowException error)
{
Console.WriteLine($"caught {error.GetType().Name}");
}
dotnet run
caught OverflowException
The try and catch are there
because the exception would otherwise end the program; the part on
exceptions reads them in
full. The opposite keyword is unchecked, which is the
default outside a checked block, and
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
makes every arithmetic operation of a project checked.
The arithmetic that most often overflows in practice is a multiplication of
two values that are each fine: 100000 * 100000
fits in a long and not in an
int. A checked block around a calculation that
matters is cheaper than the bug it prevents.
Exercises
- Change int max to long max in the second program. Why does the last line change?
- Add byte small = 255; and small++ in a checked block. Which exception do you get?
- Compute 100000 * 100000 as an int and as a long. What does each print?
- Put the whole project in checked mode with the property and run the wrap-around program again. What changes?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the range of int?
Answer
-2 147 483 648 to 2 147 483 647
int is a signed 32-bit integer, so it spans about minus two billion to plus two billion; the widest range is long and the smallest short.
-
What does this program print?
int max = int.MaxValue; Console.WriteLine(max + 1);Answer
-2147483648
The sum is computed on a variable at run time, so it wraps to the smallest int instead of failing.
-
What does this build report?
int tooBig = int.MaxValue + 1; Console.WriteLine(tooBig);Answer
error CS0220: The operation overflows at compile time in checked mode
A constant expression is evaluated in checked mode, so the overflowing sum is a compile-time error.
-
What does this program print?
checked { int max = int.MaxValue; Console.WriteLine(max + 1); }Answer
The program throws OverflowException
A checked block turns the run-time overflow into an OverflowException, and nothing was caught here.
-
Which literal is a long?
Answer
9000000000L
The L suffix makes a long literal; 42 is an int, 42.0 a double and "42" a string.
-
What does this program print?
byte b = 255; b++; Console.WriteLine(b);Answer
0
byte wraps at 255 to 0 by default; only a checked block would turn that into an exception.
-
Which type holds a count that may reach ten billion?
Answer
long
Ten billion is past the 2 147 483 647 limit of int and fits in a long.
-
What does this program print?
int a = 100000; int b = 100000; Console.WriteLine(a * b);Answer
1410065408
The product does not fit in an int, so it wraps to 1410065408; a long cast on either side would keep 10000000000.
-
What does the property CheckForOverflowUnderflow do?
Answer
It makes the arithmetic of the project checked by default
The property is the project-wide form of wrapping the code in checked, which the SDK names CheckForOverflowUnderflow.
-
What does this program print?
Console.WriteLine(sizeof(int)); Console.WriteLine(sizeof(long));Answer
4 / 8
sizeof of a built-in numeric type gives its size in bytes, which is 4 for int and 8 for long.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev