Difference between declaring variables before or in loop?

前端 未结 25 2550
长发绾君心
长发绾君心 2020-11-22 02:37

I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A (q

25条回答
  •  庸人自扰
    2020-11-22 03:25

    This is a gotcha in VB.NET. The Visual Basic result won't reinitialize the variable in this example:

    For i as Integer = 1 to 100
        Dim j as Integer
        Console.WriteLine(j)
        j = i
    Next
    
    ' Output: 0 1 2 3 4...
    

    This will print 0 the first time (Visual Basic variables have default values when declared!) but i each time after that.

    If you add a = 0, though, you get what you might expect:

    For i as Integer = 1 to 100
        Dim j as Integer = 0
        Console.WriteLine(j)
        j = i
    Next
    
    'Output: 0 0 0 0 0...
    

提交回复
热议问题