faqts : Computers : Programming : Languages : Asp : ASP/VBScript : Language and Syntax

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

11 of 12 people (92%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

Is there a difference between if you do or do not use Dim to declare variables?

Jun 7th, 2003 16:57
Sven Glazenburg, Luiz Paulo Rosa, Ahmed Salie,


!! PLEASE READ THE SECOND EDIT TO FIND OUT WHY YOU SHOULD USE DIMS AND 
OPTION EXPLICIT !!
If you use 'Option Explicit', you must declare all variables. There is 
no difference if you do not use.
Is always good to use 'Option Explicit' when programming in VBScript. 
It prevents typing errors and forces you to know which variables 
you're 
using.
[EDIT]
Besides the fact that it is good practise and prevents typing errors, 
declaring variables (and setting Option Explicit in particularly) also 
tells the ASP compiler to not look for and maybe declare a variable at 
compile time. Your code will therefore run (or more precise compile) 
faster, even though it might not be a noticable change.
[/EDIT]
[EDIT]
Also, not declaring variables may get you into trouble with using the 
same variablenames in different scopes. Consider the following piece 
of example code (it does not do anything interesting, it's just to 
show you):
<%
  function GetSomething()
    s=""
    for i=1 to 10
      s = s & i
    next
    GetSomething = s
  end function
  for i=1 to 10
    response.write GetSomething & "<br>"
  next
%>
In this example, you would expect it to output 10 lines containing 
12345678910. However, if you run it, it will only output 1 of those 
lines... What happened?
It has to do with variablenames and scope. In this examplecode, I used 
the same variable in and outside of functions, however, since I have 
not declared them anywhere, the ASP compiler dims the variable for me 
the first time it encounters it, which is at the for-statement outside 
the function. It is thereby declared as a global variable.
This is where things go wrong, because the function expects the 
variable to be a local one, and not a global one. As the function runs 
for the first time, i is set to 10 in the end. This means that when it 
reaches the next-statement outside the function, it will not loop 
again, since 10 is already reached.
So, the solution is to at least dim your variables, but preferably use 
Option Explicit. Why wouldn't you? It's just a single line of code!
This code WILL run fine:
<%
  option explicit
  function GetSomething()
    dim s, i
    s=""
    for i=1 to 10
      s = s & i
    next
    GetSomething = s
  end function
  dim i
  for i=1 to 10
    response.write GetSomething & "<br>"
  next
%>
Hope this helps you all clarify why you SHOULD use Dim's and Option 
Explicit!
Cheers,
Sven Glazenburg
[/EDIT]



© 1999-2004 Synop Pty Ltd