ASP: Constants

In our Variables tutorial we have shown you, how variables are used as containers to store information. Well so does a constant. The main difference between constants and variables is that constant value can not be changed in the process of running program. Constants always keep their value assigned while declaration.

Have a look at the following example where  the value of the myText variable changes throughout the script.

 
<%@ LANGUAGE="VBSCRIPT" %>
<%
'commented lines starting with an apostrophe
'are not executed in VBScript
'first we will declare a variable

Dim myText
'Let's assign a value to our variable
myText = "Good Morning!"
'now the myText variable contains the value Good Morning
Response.Write(myText)
'the output will be Good Morning
'next we will assign a new value to our variable

myText = "Have a nice day!"
'now the myText variable contains the value Have a nice day
Response.Write(myText)
'the output will be Have a nice day
%>

The value stored in a constant cannot be changed after it has been declared.  If we attempt to re-assign the value of the constant as we did with the value of the variable we’ll get a run time error. To declare a constant in VBScript we use the Const keyword.

 
'the constant is declared and assigned the value all on the same line
Const myConst = myText"
'it is allowed to declare a few constants on the one line
Const PI = 3.14159, Wg  = 2.78

The following example demonstrates the advantage of constants: during the calculations with number PI, you can type in your code only constants name instead of typing this number each time.

 
...

vCircle = PI * vRadius^2

admin

admin

Leave a Reply

Your email address will not be published.