15. Scope

Scope refers to the enclosing context where values and expressions are associated. So where I decide to place my variable declarations from the previous lesson becomes important because if I put them in the wrong place, I might not be able to refer to them later in my code.

Global Declarations
If I place a variable declaration outside of any sub-procedure (but inside the Class of course) then that variable has global scope…in other words, it is accessible everywhere inside the Class. i.e:

Public Class frmTicTacToe

   'GLOBAL DECLARATIONS
   Dim xWins As Integer
   Dim oWins As Integer

   Private Sub frmTicTacToe_Load( ...

      :

   End Sub

   :

End Class

Local Declarations
If I place a variable declaration inside a sub-procedure then no other sub-procedure is able to “see” that variable and thus it only exists during the running of that sub-procedure. i.e:

Public Class frmTicTacToe

   Private Sub frmTicTacToe_Load( ...

      'LOCAL DECLARATIONS
      Dim xWins As Integer
      Dim oWins As Integer

      :

   End Sub

   :

End Class

It may not seem like a very large change but you will very quickly realise the pros and cons of each. For our TicTacToe program, we need our first two variables to be Global…i.e:

Okay, hopefully you’re now getting the hang of using the code window in VB and so from here on in I won’t include any screen shots but instead simply give you directions on the code you need to include.

Leave a Comment

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>