Variable Declaration

This tip covers variable declaration in Visual Basic.

Variable Declaration

Most high level programming languages force the developer to explicitly declare a variable before using it. Visual Basic is a notable exception. In fact, by default, VB's installation leaves the Visual Basic environment in a state where variable declaration is not required.

After installing Visual Basic, immediately select Tools-Options and check on REQUIRE VARIABLE DECLARATION.

Selecting this option causes Visual Basic to insert the statement OPTION EXPLICIT into the General Declarations Section of each module in your project. The result is that an attempt to refer to a variable in code without first declaring it results in a compiler error.

What's the big deal, you might ask? Is there really a harm in leaving this option checked off? Suppose you use a variable in code that you haven't declared? Visual Basic is a programmer friendly language-won't VB take care of it?

The answer is yes. VB will take care of it, but the price of a mistake on your part can be huge.

For instance, suppose you assign a value to a variable called sngUnitPrice like this...

sngUnitPrice = 13.48

And then later in your code you attempt to refer to this variable in a calculation, but accidentally refer to it by an incorrect name, for instance sngUnitCost (yes, it can happen!)

sngTotalPrice = sngUnitCost * m_intQuantity

You're expecting the program to come up with a valid price. Instead, the result will be zero, since the value of the incorrectly named variable sngUnitCost is zero!

When you tell VB to enforce variable declaration, errors like these are caught at compile time, potentially preventing disastrous results from occurring.
-------------------------------------------------------------
Written by John Smiley, MCP, MCSD and MCT, is an adjunct professor of Computer Science at Penn State University in Abington, Philadelphia University, and Holy Family College, and has been teaching computer programming for nearly 20 years. He also teaches a number of very popular online courses at SmartPlanet and ElementK. In addition, John is the author of four very popular Visual Basic books, and is reportedly the first guest to write a computer program live on ZDTV's Screen Saver's show.

John Smiley is president of Smiley and Associates http://www.johnsmiley.com/smass/smass.htm, a computer consulting firm located in New Jersey.

This was first published in July 2000

Dig deeper on Win Development Resources

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

SearchCloudComputing

SearchSoftwareQuality

SearchSOA

TheServerSide

SearchCloudApplications

Close