What's Wrong With this Code? (#3)

Tuesday, August 15, 2006

Here is a Visual Basic program with bowling scores in a multi-dimensional array. Two players bowled three games each. The program tries to display the total score for each bowler, but has a small problem. Can you spot it?

Module Module1

  
Sub Main()

    
Dim allScores As Integer(,) = _
        {{101, 128, 143}, {123, 115, 116}}

    
' for each player
    For i As Integer = 0 To allScores.GetUpperBound(0)

      
Dim score As Integer

      ' for each game
      For j As Integer = 0 To allScores.GetUpperBound(1)
        score = score + allScores(i, j)
      
Next

      Console.WriteLine("Player {0} score: {1}", i + 1, score)

    
Next

  End Sub

End
Module


Comments
Eber Irigoyen Tuesday, August 15, 2006
due to the scope, variable score needs to be initialized to zero
Abhijit Tuesday, August 15, 2006

variable score should be initialised to 0

Dim score As Integer = 0
Geoff Appleby Tuesday, August 15, 2006
Ha, an easy one :)

score might look like it's declared inside the first loop, but when compiled the declaration moves to the top of the mothod.

The end result is that the printed score for player 2 is the actually the entire sum.

By modifying it to be Dim score as Integer = 0 (or exlicitly assinging 0 on the next line) the declaration is still at the top, but the assignment to 0 happens on every iteration.
scott Tuesday, August 15, 2006
You guys nailed it! Too easy!
Justin King Tuesday, August 15, 2006
It's not written in C# :P
James Tuesday, August 15, 2006
It is written in Visual Basic?

:o)
scott Tuesday, August 15, 2006
James, Justin:

In C# this would yield a "use of unassigned local" warning. In a sense you are right.
Eric D. Burdo Tuesday, August 15, 2006
Geoff... VB Classic doesn't have scope level variables.

VB.Net does. So the declaration doesn't get moved to the top. It stays inside the block it is declared in.

So you need to either a) Declare the score at the top, then initialise to 0 inside the loop, or b) initialise to 0 inside the loop when you declare the score variable.

I would prefer method b if I didn't need the score outside of the first loop.
marshall Tuesday, August 15, 2006
can anyone tell me a reason why vb.net behaves like this?

i can't see any good reason for keeping a variables value when it goes out of scope.
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!