0

Following is a piece of code:

    {
        int counter = 1;
        try
        {
            while (true) 
                counter*=2;
        }
        catch (Exception)
        {
            Console.WriteLine(counter);
            Console.ReadLine();
        }
    }

When I run this code, after a few iterations, value of 'counter' becomes 0. I don't understand why it is so?

Palak.Maheria
  • 1,497
  • 2
  • 15
  • 32

2 Answers2

10

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
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
3

When counter reach the int.MaxValue then counter * 2 becomes a negative integer.

Then when counter reach int.MinValue then counter * 2 becomes 0.

Then on each iteration you have 0 * 2 = 0, no exception to throw.