Use checked
for the overflow exception to be thrown:
checked {
int counter = 1;
try {
while (true)
counter *= 2;
}
catch (Exception) { // Actually, on integer overflow
Console.WriteLine(counter);
Console.ReadLine();
}
}
Edit: what's going on.
Fact: integer multiplication by 2 is equal to left shift by 1, i.e.
counter * 2 == counter << 1
In your case (let counter
be represented as binary)
00000000000000000000000000000001 // initial, just 1
00000000000000000000000000000010 // 1st itteration (shifted by 1)
00000000000000000000000000000100 // 2nd itteration (shifted by 2)
...
10000000000000000000000000000000 // 31st itteration (shifted by 31)
the next, 32nd itteration can cause either integer overflow or when
unchecked
just push the leftmost 1 out
0000000000000000000000000000000 // 32nd itterartion, now we have 0