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
variable score should be initialised to 0
Dim score As Integer = 0
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.
:o)
In C# this would yield a "use of unassigned local" warning. In a sense you are right.
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.
i can't see any good reason for keeping a variables value when it goes out of scope.