To Be or Not to Be? Why Variable Declaration is a "Good Thing".


By default Visual Basic does not require you to declare your variables. So, you can do the following:

Private Sub Form_Load()
     x = 1
     y = 2
     z = x + y
     MsgBox "x + y = " & z
End Sub

So, cool right? You don’t have to tell VB that you’re adding numbers, also known as type coercion. You save typing too, because you don’t have those extra lines of code for your variable declarations. Not cool at all, not in the long run.

First, x, y and z although they only hold Integers, are taking up the same amount of space three Variants would require. A variable declared as an Integer takes up 2 bytes, while a variable that is not declared, by default, is a Variant; with numeric values this Datatype takes up 16 bytes of storage. There's a big difference between 6 bytes and 48 bytes. Space may not be the commodity it used to be, in this day of multiple gigabyte hard drives, but choosing the right datatype is still an important consideration.

Second, imagine that you have an application with 500+ lines of code. It would be easy to lose track of what variables you’re using. That’s why immediately after installing VB, go to Tools – Options, and on the Editor tab check off "Require Variable Declaration". Then re-start VB. You will now have "Option Explicit" under your General Declarations, in the code window. And VB will tell you when one of your variables does not exist, by giving you the error "Variable not defined."

It’s a "Good Thing".

Option Explicit
     Public x As Integer, y As Integer, z As Integer
Private Sub Form_Load()
     x = 1
     y = 2
     z = x + y
     MsgBox "x + y = " & z
End Sub


Back to top
Home