Page

4.2.1- Using Option Explicit

  by NT Community Manager.  

PublicCategorized as 04. Variables.

Not tagged.
<< 4.2.0- Declaring VariablesChapter44.3.0- Arithmetic and Comparison Operators >>

Using Option Explicit

Option Explicitis very simple. All you need to do is add this line to the beginning of yourASP scripts: then, every variable in the program must be explicitly declared inthe code before it's used. If an implicitly declared variable is used, then Option Explicit generatesan error highlighting the particular omission.

 

Here's an example of how OptionExplicit is useful in keeping errors down.Consider the following program:

 

Option Explicit

Dim intHeight, intWidth, intTotal

intHeight = 150

intWidth = 140

intTotal = (intHeight * (intWidth+40))/(intHeigth+intWidth) 

 

In such a short code fragment, you can probably spot prettyquickly that we've misspelled intHeight in thesecond usage on the last line. However, imagine that this fragment of code isburied in a list of 100 variables, about 50 lines into the page. Would you beable to spot it so quickly then?

 

With the Option Explicit line, this error would be detectedimmediately, when the script is run, as an illegal implicit declaration.Without Option Explicit,the implicit declaration is entirely legal, so your page would execute withoutan error. ASP will execute the page thinking that in fact you wanted to createa intHeigth as a second variable, completelydifferent to intHeight. In fact, the only clue tothe error is the value assigned to intTotal,which is calculated with the value of intHeigth(i.e. 0) instead of intHeight (i.e. 150). Indeed,if you didn't know what value to expect for intTotal,then you might not even notice the mistake at all!

When you place Option Explicitin a script, you must make sure it is the first line and not as follows:

 

Dim intHeight, intWidth, intTotal

Option Explicit

intHeight = 150

intWidth = 140

intTotal = (intHeight * (intWidth+40))/(intHeigth+intWidth) 

 

The position of Option Explicit in this script will actually cause a syntaxerror. Moreover, on the server-side, in ASP, OptionExplicit must come even before the first line of HTML:

 

<%Option Explicit%>

<HTML>

...

 

When you think about it, where else could it go? Scripts arerun from top to bottom. If you want it to check for Dimstatements, you had better tell it to do that before it starts reading thescript. In ASP, the ASP is processed before the HTML, so it has to come beforethe HTML.

<< 4.2.0- Declaring VariablesChapter44.3.0- Arithmetic and Comparison Operators >>

Copyright © 2003 by Wiley Publishing, Inc.

Powered by Near-TimeTerms of Services | Privacy Policy | Security Policy |