Scope Release

Scope Release

Understanding Variable Scope and Duration in Visual Basic 6

Variable Scope


The scope of a variable determines where you can access that variable in your code. If a variable is in scope you can read or set it's value. If it is out of scope you will not be able to access it.

There are three types of scope for variables in Visual Basic:

  • Global Scope
    Global variables are in scope anywhere in your application.
  • Module Scope
    Module level variables are in scope anywhere within the module where they are declared.
  • Local Scope
    Local variables are only in scope within the procedure where they are declared.

Global Scope


Global variables are available anywhere in your program. Any line of code in any procedure can read or write the value of the variable. While convenient, it is considered bad programming practice to overuse global variables and some programmers (myself included) make a considerable effort to avoid them entirely.

To create a global variable, declare it in the declarations section of a standard module using the Global or Public keyword.

Module Scope


Module level variables are available to any code within the module where they are declared. While using global variables is considered bad programming practice, using module level variables is not. Module level variables allow you to share data between procedures without exposing that data to every procedure in the application.

To create a module level variable, declare it in the declarations section of a module using either the Dim or Private keyword.

Local Scope


Local variables are only availabe to the procedure in which they are created. Local variables are the most restricted in scope - not even other procedures in the same module may read or modify local variables.

You create local variables by declaring them with the Dim or Static keyword within the body of a Sub, Function, or Property procedure.

Variations


There are a few variations from the basic scoping rules:

  • Public Variables in Class Modules
    Unlike public variables in standard modules, public variables in Class modules are only in scope when an object variable representing the class is in scope. For example, you may have a CPerson class with a public FirstName variable. CPerson:FirstName is public, but it is only available if there is an object variable based on the CPerson class currently in scope. You can't simply declare the variable in the class module and then reference it without first creating a CPerson object.
  • Public Variables in Form Modules
    Although forms can be thought of as being derived from classes, Visual Basic treats forms differently. Unlike a class, you are not required to declare form object variables (although it is considered good programming practice to do so). If you reference a public variable in a form from anywhere in your code, a copy of the form is created for you by Visual Basic. As you might imagine, this can lead to some unintended behavior if you are not aware of it.
  • Shadowing
    If variables with the same name are declared so that more than one of them is within scope when the variables are referenced, the most local copy is used. For example, if you declare a variable named sName in a procedure, and also have an sName variable declared as Private in the declarations section of the same module, as well as a global sName variable declared in another module, the following rules would apply:
    • Within the procedure where sName is declared, the local copy of sName would be used.
    • Elsewhere within the module with the private sName variable the module level variable would be used.
    • Code in other modules will use the global sName variable.

You can avoid the problem of name shadowing easily by using a naming convention that adds a prefix indicating the scope of a variable. A common convention is to prefix module level variables with "m" and global variables with "g". Local variables receive no prefix indicating scope.

Comments


Good programming practice dictates that you should try to limit the scope of your variables to the most restrictive scope you can use. If possible, data that needs to be shared between procedures should be passed in the parameter list. This is an explicit data sharing mechanism and there is no doubt about how the procedure obtains it's values.

For data that needs to be maintained independently of any procedure, module level variables are the next best choice. While module level variables are exposed within the module, they are hidden to the rest of the application. This encapsulates data that is used by a module within the module and does so privately. No code outside of the module is even aware of the existence of private module data and thus cannot alter it.

Global variables should generally be avoided. While they are convenient for sharing data between modules, they are as dangerous as they are easy. Because any procedure anywhere in the application can change a global variable, you may have code changing globals in unexpected ways - leading to unpredictable behavior in the application and extremely difficult debugging.

Don't, however, confuse global variables with global constants. Just as it is advisable to avoid the use of global variables, it is recommended to use constants wherever possible. Since constants cannot be changed at run-time, the problems of global variables are avoided. The primary purpose of constants is avoiding "magic numbers." Magic numbers are values like coded property settings. For example, a combo box can be assigned one of three styles: dropdown combo (a normal text box with a drop down list), simple combo (the list is always displayed), and dropdown list (the user must choose a value in the list). These styles have the values 0, 1, and 2 respectively. Instead of using the actual values, using symbolic constants adds a level of abstraction to the code. For the combo box, VB supplies the intrinsic constants vbComboDropdown, vbComboSimple, and vbComboDropdownList. Using one of these constants makes the code easier to read because an English-like word replaces an arbitrary number.

Variable Duration


Variable duration, or lifetime, indicates how long a variable exists in the life of a program. A variable may have a duration ranging from as long as the lifetime of an application or as short as the lifetime of a single procedure. Duration is closely related to variable scope because the location where a variable is declared can affect both.

Normally, all variables declared at the module level have a duration of the lifetime of an application, and variables declared within a procedure only exist while the procedure is executing. There are, however, a few exceptions to this general rule.

  • Static Variables
    You can declare local variables (variables declared within a procedure) or even an entire procedure as Static. Static variables retain their values between procedure calls. A common use of static variables is as control flags to prevent unbounded recursion (a recursive function is a function that calls itself - if not controlled, a recursive function can quickly consume all of the available space on the stack, leading to a stack overflow error), control flags for write-once property settings, and so on.
  • Class Modules
    Module level variables declared in class modules exist for the lifetime of the class objects. Remember that with classes you cannot directly access code or data within the module without first creating an instance of an object defined by the class.
  • Form Modules
    Form modules, like class modules, require that an instance of the form be created before its code and data can be used. However, VB treats form modules somewhat differently and will automatically create an instance of a form if any propery of the form is referenced in your code. Also remember that module level variables in forms are not destroyed until the reference to the form object is released by setting the form to Nothing. Unloading a form does not clear the value of the form's module level variables.

Summary


Key concepts to remember about variable scope and duration are:

  • Variable scope determines where in your code you can "see" a variable.
  • Variable duration indicates how long a variable exists in the lifetime of a program.
  • VB's rules for shadowing state that the most local copy of a variable will be the copy used.
  • Special rules apply for variables in form and class modules that affect both the scope and duration of the variables in the form or class.
  • Good programming practice dictates that you should try to limit the scope of your variables to the smallest range possible.

Original article could be found on our site, at: www.visualbasicempire.com

About the Author

Visual Basic Empire

Scope and Lateral Release of the Knee

NEW AIRSOFT PISTOL HAND GUN LED LIGHT  LASER W BBS TACTICAL SIDE ARM SNIPER
NEW AIRSOFT PISTOL HAND GUN LED LIGHT LASER W BBS TACTICAL SIDE ARM SNIPER
Paypal   US $.01
MUSIC CD PEARL JAM TEN GUARANTEED EXCELLENT NO RESERVE
MUSIC CD PEARL JAM TEN GUARANTEED EXCELLENT NO RESERVE
Paypal   US $4.99
NAGLFAR HARVEST BRAND NEW SEALED NR
NAGLFAR HARVEST BRAND NEW SEALED NR
Paypal   US $49.95
Green Day Rock Band Wii NEW
Green Day Rock Band Wii NEW
Paypal   US $15.72
Toy Story 2 DVD 2005 2 Disc Set Special Edition
Toy Story 2 DVD 2005 2 Disc Set Special Edition
Paypal   US $8.50
The Spiderwick Chronicles DVD 2008 Widescreen Great for kids
The Spiderwick Chronicles DVD 2008 Widescreen Great for kids
Paypal   US $.99
Us by Peter Gabriel Cassette 1992 Geffen
Us by Peter Gabriel Cassette 1992 Geffen
Paypal   US $.99
So by Peter Gabriel Cassette May 1986 Geffen
So by Peter Gabriel Cassette May 1986 Geffen
Paypal   US $.99
Fable II Xbox 360 2008
Fable II Xbox 360 2008
Paypal   US $4.75
Significant Other Edited] ECD] by Limp Bizkit CD Jun 1999 Interscope USA
Significant Other Edited] ECD] by Limp Bizkit CD Jun 1999 Interscope USA
Paypal   US $.99
Yoshis Safari Super Nintendo SNES Video Game
Yoshis Safari Super Nintendo SNES Video Game
Paypal   US $7.95
PEARL JAM Vitalogy 1994 Case CD  BOOKLET Nice Betterman Etc
PEARL JAM Vitalogy 1994 Case CD BOOKLET Nice Betterman Etc
   US $8.00
USB VHS to DVD Converter Video Grabber Capture Record
USB VHS to DVD Converter Video Grabber Capture Record
Paypal   US $28.99
Planet Earth The Complete Collection Blu ray Disc 2007 4 Disc Set
Planet Earth The Complete Collection Blu ray Disc 2007 4 Disc Set
Paypal   US $15.00
So by Peter Gabriel CD May 1986 Geffen
So by Peter Gabriel CD May 1986 Geffen
Paypal   US $9.99
Canon PowerShot A85 40 MP Digital Camera Silver USER CAMERA GOOD IMAGES
Canon PowerShot A85 40 MP Digital Camera Silver USER CAMERA GOOD IMAGES
Paypal   US $25.00
Tippmann 98 Custom Pro PLATINUM SERIES eTrigger w ACT
Tippmann 98 Custom Pro PLATINUM SERIES eTrigger w ACT
Paypal   US $115.00
Toy Story 2 DVD SEALED New  in Widescreen
Toy Story 2 DVD SEALED New in Widescreen
Paypal   US $6.50
Tippmann 98 Custom PLATINUM SERIES w Response Trigger ACT
Tippmann 98 Custom PLATINUM SERIES w Response Trigger ACT
Paypal   US $89.50
SUPER STAR WARS RETURN OF THE JEDI for Super Nintendo SNES Good Condition NR
SUPER STAR WARS RETURN OF THE JEDI for Super Nintendo SNES Good Condition NR
Paypal   US $2.42
Driver X12 Titanium 12000 lb 12 volt Electric Self Recovery Winch 12v 12000 12K
Driver X12 Titanium 12000 lb 12 volt Electric Self Recovery Winch 12v 12000 12K
Paypal   US $374.95
300 WS
300 WS
Paypal   US $3.00
Lain Vol 4 Reset DVD 1999
Lain Vol 4 Reset DVD 1999
Paypal   US $15.00
300 DVD 2007 Widescreen
300 DVD 2007 Widescreen
Paypal   US $1.50
Toy Story 2 DVD 2010 Special Edition
Toy Story 2 DVD 2010 Special Edition
Paypal   US $10.00
The Good Shepherd DVD 2007 Anamorphic Widescreen
The Good Shepherd DVD 2007 Anamorphic Widescreen
Paypal   US $4.00
17000 lb Electric Self Recovery Winch for Jeep Truck Trailer SUV 17000 17K 12v
17000 lb Electric Self Recovery Winch for Jeep Truck Trailer SUV 17000 17K 12v
Paypal   US $424.95
LOUIS ARMSTRONG cd The Millennium Collection free ship
LOUIS ARMSTRONG cd The Millennium Collection free ship
Paypal   US $5.25
300 HD DVD 2007
300 HD DVD 2007
Paypal   US $4.99
Ten by Pearl Jam CD Aug 1991 Epic Associated Used CD
Ten by Pearl Jam CD Aug 1991 Epic Associated Used CD
Paypal   US $.99
The Chronicles of Narnia The Lion The Witch and the Wardrobe DVD 2006
The Chronicles of Narnia The Lion The Witch and the Wardrobe DVD 2006
Paypal   US $.99
Far Infrared Tourmaline Double Shoulder auto heat pad
Far Infrared Tourmaline Double Shoulder auto heat pad
Paypal   US $8.66
SIMMONS EXTRA TALL 1 inch SCOPE RINGS For 50mm OBJECTIVE Matte Black NEW
SIMMONS EXTRA TALL 1 inch SCOPE RINGS For 50mm OBJECTIVE Matte Black NEW
Paypal   US $11.39
Cullmann TITAN tripod with CT 30 3 way pan head  VERY stable tripod
Cullmann TITAN tripod with CT 30 3 way pan head VERY stable tripod
Paypal   US $118.95
Sarafina The Sound of Freedom Original Soundtrack] CD Sep 1992 Qwest
Sarafina The Sound of Freedom Original Soundtrack] CD Sep 1992 Qwest
Paypal   US $.99
Zeikos Tripod for Digital Camera DSLR Scope etc Tommy Jordans
Zeikos Tripod for Digital Camera DSLR Scope etc Tommy Jordans
Paypal   US $30.51
Lock On MODERN AIR COMBAT sim game NEW PC CD ROM
Lock On MODERN AIR COMBAT sim game NEW PC CD ROM
Paypal   US $4.38
Tempted by Marty Stuart CD Jan 1991 MCA USA
Tempted by Marty Stuart CD Jan 1991 MCA USA
Paypal   US $19.99
There Will Be Blood DVD 2009 DANIEL DAY LEWIS TOM  JERRY
There Will Be Blood DVD 2009 DANIEL DAY LEWIS TOM JERRY
Paypal   US $4.00
Super Nintendo SNES Super NES Super Scope 6 Video Game
Super Nintendo SNES Super NES Super Scope 6 Video Game
Paypal   US $.01
Pearl Jam Ten
Pearl Jam Ten
Paypal   US $3.00
Super Nintendo SNES Video Game Tin Star TinStar
Super Nintendo SNES Video Game Tin Star TinStar
Paypal   US $15.00
Super Nintendo Video Game SNES X Zone
Super Nintendo Video Game SNES X Zone
Paypal   US $.99
Let Freedom Ring Digipak]  by Chuck Prophet CD O
Let Freedom Ring Digipak] by Chuck Prophet CD O
Paypal   US $13.50
Led Zeppelin IV
Led Zeppelin IV
Paypal   US $3.00
Carnival Vol 2 Memoirs of an Immigrant by Wyclef Jean CD Dec 2007
Carnival Vol 2 Memoirs of an Immigrant by Wyclef Jean CD Dec 2007
Paypal   US $4.00
Belt Holster for RUGER 22 6 7 8 WITH SCOPE
Belt Holster for RUGER 22 6 7 8 WITH SCOPE
Paypal   US $17.70
Rebel Without a Cause VHS 1990  Legendary JAMES DEAN
Rebel Without a Cause VHS 1990 Legendary JAMES DEAN
Paypal   US $9.99
High School Musical 3 Senior Year Blu ray Disc 2009
High School Musical 3 Senior Year Blu ray Disc 2009
Paypal   US $3.00
There Will Be Blood DVD 2009
There Will Be Blood DVD 2009
Paypal   US $.99
Rise of the Argonauts Used Xbox 360 Game
Rise of the Argonauts Used Xbox 360 Game
Paypal   US $6.99
Planet Earth The Complete Attenborough BBC DVD Series
Planet Earth The Complete Attenborough BBC DVD Series
Paypal   US $5.50
TRIJICON AccuPoint Mount Base QUICK RELEASE Flattop Mount FROM WESTLAKE
TRIJICON AccuPoint Mount Base QUICK RELEASE Flattop Mount FROM WESTLAKE
Paypal   US $255.00
NAKED RASHOMON of Japan JAPANESE Erotic EROTICA Movie VINTAGE ASIAN Video on DVD
NAKED RASHOMON of Japan JAPANESE Erotic EROTICA Movie VINTAGE ASIAN Video on DVD
Paypal   US $17.95
Toy Story 2 Blu ray DVD 2011 4 Disc Set Includes Digital Copy 3D
Toy Story 2 Blu ray DVD 2011 4 Disc Set Includes Digital Copy 3D
Paypal   US $18.50
300 Special Edition 2 Disc DVD Set Mint
300 Special Edition 2 Disc DVD Set Mint
Paypal   US $3.00
Cabelas Dangerous Hunts 2011 Game  Gun Xbox 360 2010
Cabelas Dangerous Hunts 2011 Game Gun Xbox 360 2010
Paypal   US $45.00
Ben Hur DVD 2001
Ben Hur DVD 2001
Paypal   US $1.25
Gears of War Xbox 360 2006 FREE SHIPPING
Gears of War Xbox 360 2006 FREE SHIPPING
Paypal   US $8.37
SCHOENBERG Theme and Variations for Band MOGENSEN Aerial Fantasy SEALED
SCHOENBERG Theme and Variations for Band MOGENSEN Aerial Fantasy SEALED
Paypal   US $13.09
300 DVD 2007 2 Disc Set Special Edition
300 DVD 2007 2 Disc Set Special Edition
Paypal   US $4.99
Ten by Pearl Jam CD Aug 1991 Epic Associated
Ten by Pearl Jam CD Aug 1991 Epic Associated
Paypal   US $2.00
Savatage Gutter Ballet CD
Savatage Gutter Ballet CD
Paypal   US $9.82
Canon Powershot A85 4MP Digital Camera Complete kit with filters  extra lenses
Canon Powershot A85 4MP Digital Camera Complete kit with filters extra lenses
Paypal   US $132.00
The Chronicles of Narnia The Lion The Witch and the Wardrobe DVD 2006 E
The Chronicles of Narnia The Lion The Witch and the Wardrobe DVD 2006 E
Paypal   US $4.00
Ben Hur DVD 2011 2 Disc Set Fiftieth Anniversary
Ben Hur DVD 2011 2 Disc Set Fiftieth Anniversary
Paypal   US $6.00
Significant Other PA] ECD] by Limp Bizkit CD Jun 1999 Interscope USA
Significant Other PA] ECD] by Limp Bizkit CD Jun 1999 Interscope USA
Paypal   US $5.99
NEW Planet Earth Complete BBC Series Bluray 5 disc set
NEW Planet Earth Complete BBC Series Bluray 5 disc set
Paypal   US $16.49
Adaptation VHS Video Nicolas Cage Meryl Streep Chris Cooper Orchids Oscar Winner
Adaptation VHS Video Nicolas Cage Meryl Streep Chris Cooper Orchids Oscar Winner
Paypal   US $3.00
Illadelph Halflife PA] by Roots The CD Sep 1996 DGC
Illadelph Halflife PA] by Roots The CD Sep 1996 DGC
Paypal   US $5.49
Peter Gabriel by Peter Gabriel CD Sep 1988 Atco USA
Peter Gabriel by Peter Gabriel CD Sep 1988 Atco USA
Paypal   US $4.49
2 Leupold Scope Mounts STD BR 1885 Browning High Wall and QR BR Lever action
2 Leupold Scope Mounts STD BR 1885 Browning High Wall and QR BR Lever action
Paypal   US $9.95
DEATH CHANTS lp time lag 288copies ASWARA MV  EE NNCK hazy psych folk drone
DEATH CHANTS lp time lag 288copies ASWARA MV EE NNCK hazy psych folk drone
Paypal   US $13.99
Molle Airsoft Versatile QD Drop Leg Pistol Holster Olive Drab
Molle Airsoft Versatile QD Drop Leg Pistol Holster Olive Drab
Paypal   US $19.99
The Curious Case of Benjamin Button DVD 2009
The Curious Case of Benjamin Button DVD 2009
Paypal   US $6.99
Molle Airsoft Versatile QD Drop Leg Pistol Holster ACU
Molle Airsoft Versatile QD Drop Leg Pistol Holster ACU
Paypal   US $19.99
CD Pearl Jam Ten 1991
CD Pearl Jam Ten 1991
Paypal   US $5.99
Vitalogy by Pearl Jam CD Dec 1994 Epic USA
Vitalogy by Pearl Jam CD Dec 1994 Epic USA
Paypal   US $1.99
Double Ring Riser Scope Mount 25mm ring Rail Tops Thumb Release weaver mount
Double Ring Riser Scope Mount 25mm ring Rail Tops Thumb Release weaver mount
Paypal   US $21.99
5 PG MAY 2012 WHOLE UNCUT COUPON INSERTS
5 PG MAY 2012 WHOLE UNCUT COUPON INSERTS
Paypal   US $.99
The Cherrytree Sessions The Cherrytree Sessions

Sale Price: $14.58

 
The Cherrytree Sessions The Cherrytree Sessions

Sale Price: $9.00

 
Robyn (with Bonus Tracks) Robyn (with Bonus Tracks)

Sale Price: $4.37

 
Security Equipment Sabre 3-In-1 Self Defense Spray Pink Camo Pocket Key Case Red Pepper Security Equipment Sabre 3-In-1 Self Defense Spray Pink Camo Pocket Key Case Red Pepper

List Price: $32.20
Sale Price: $16.99
You save: $15.21 (47%)

 
Security Equipment Sabre 3-In-1 Self Defense Spray Key Ring Unit Red Pepper Cs Military Tear Gas Security Equipment Sabre 3-In-1 Self Defense Spray Key Ring Unit Red Pepper Cs Military Tear Gas

List Price: $28.62
Sale Price: $14.99
You save: $13.63 (48%)

 
Security Equipment Sabre 3-In-1 Self Defense Spray Black Pocket Key Case Red Pepper Tear Gas Security Equipment Sabre 3-In-1 Self Defense Spray Black Pocket Key Case Red Pepper Tear Gas

List Price: $30.41
Sale Price: $15.99
You save: $14.42 (47%)

 
The Opposite Sex [Remaster] The Opposite Sex [Remaster]

List Price: $26.99
Sale Price: $14.90
You save: $12.09 (45%)

 
DS Laboratories Oligo DX Cellulite Reducing Gel, 150ml Tube DS Laboratories Oligo DX Cellulite Reducing Gel, 150ml Tube

List Price: $38.50
Sale Price: $21.17
You save: $17.33 (45%)

 
DS Laboratories Oligo DX Cellulite Reducing Gel DS Laboratories Oligo DX Cellulite Reducing Gel

List Price: $48.00

 
Oligo DX® 150 ml Oligo DX® 150 ml

List Price: $48.00

 
Cstar WM-1 Swivel-style Car Window Mount Cstar WM-1 Swivel-style Car Window Mount

List Price: $29.99

 
Ravelli APGL4 New Professional 70 Ravelli APGL4 New Professional 70" Tripod with Adjustable Pistol Grip Head and Heavy Duty Carry Bag

List Price: $399.99
Sale Price: $83.33
You save: $316.66 (79%)

 
Celestron 21061 AstroMaster 70 AZ Refractor Telescope Celestron 21061 AstroMaster 70 AZ Refractor Telescope

List Price: $191.95
Sale Price: $110.00
You save: $81.95 (43%)

 
Manfrotto 701HDV Pro Fluid Video Mini Head Manfrotto 701HDV Pro Fluid Video Mini Head

Sale Price: $132.99

 
76mm ID Orion Telescope Tube Rings 76mm ID Orion Telescope Tube Rings

Sale Price: $29.99

 
298mm ID Orion Telescope Tube Rings 298mm ID Orion Telescope Tube Rings

Sale Price: $89.99

 
Orion SkyView Pro 8 EQ Reflector Telescope with FREE Drive Orion SkyView Pro 8 EQ Reflector Telescope with FREE Drive

List Price: $569.00

 
CinemaScope Four: M-G-M MOVIES Light Up the Screen CinemaScope Four: M-G-M MOVIES Light Up the Screen

List Price: $2.99

 
Empire: Total War Empire: Total War

List Price: $19.99
Sale Price: $8.45
You save: $11.54 (58%)

 
Battlefield Bad Company 2 [Download] Battlefield Bad Company 2 [Download]

List Price: $19.99
Sale Price: $14.94
You save: $5.05 (25%)

 
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay