What Does This Code Do?

“What does this code do?” is often a bit of a gotcha sort of question. OK sometimes it is a simple thing to make sure a student understands the syntax but many times it is really asking if the student understands some underlying concepts of either the programming language or how computers work. Rob Miles asked his students a question like that recently and posted it in his blog. The C# code was:

             short i;
            for (i = 0; i < 10; i--)
            {
                Console.WriteLine("i is: " + i);
            }
            Console.WriteLine("i is: " + i);

Well being the Visual Basic fan that I am I decided to write the VB version. Not so easy as it turns out. You can try a For loop and get something like this:

         Dim i As Short = 0
        For i = 0 To 10 Step -1
            Console.WriteLine("i is: " + i.ToString())
        Next i

And it looks the same but VB is too smart to run that loop. The C# for loop in this case is really as much a While loop as what I like to think about as a For loop. So you can use a loop like this one and get the same basic result as the C# code with one exception.

         Dim i As Short = 0
        While i < 10
            i -= 1
            Console.WriteLine("i is: " + i.ToString())
        End While

Yep, Visual Basic throws an exception – overflow!

So now you get a really interesting discussion. The bonus question is which way of handling the overflow is “better.” Is it a good idea to take advantage of things like C# (and I believe C, C++ and Java) allowing the wrap around to happen and treating it as if that were ok? Or is it better to throw an exception on an overflow so that the program knows something is up?

Sure the C-family way lets you do things that are cute and tricky but is that a good thing or a bad thing? How does it impact maintainability, supportability and future development? Does throwing an exception add protection or just get in the way? Feel free to discuss both sides here. Or bring it up in class and let me know what that discussion goes like. I’d be interested to here about it.