Export (0) Print
Expand All

Using Constants

Microsoft® Windows® 2000 Scripting Guide

Constants represent values that cannot change while a script is running. For example, suppose you have a script that converts Japanese yen to U.S. dollars. Assuming the current exchange rate is 1 yen for every 0.00888759 dollars, you can hard-code the literal value into the script, like the following:



curConvertedPrice = curPriceInYen * 0.00888759

Although this approach works, it does pose some potential problems:

  • Another administrator editing your script might not understand what 0.00888759 represents.

  • Exchange rates change frequently. By using the literal value, you must search the script for each occurrence of the literal value and then change this value every time the exchange rate changes. If you overlook one such occurrence, your script will no longer provide accurate information.

  • Every time you type a literal value, you risk making a mistake that can affect your calculations. For example, inadvertently typing 0.0888759 will drastically affect the equation. One thousand yen converted using the correct rate of 0.00888759 is a little less than $9. The same thousand yen converted using the incorrect rate of 0.0888759 is approximately $89.

To help overcome these problems, use constants rather than literal values. Constants have a number of advantages over literal values. Constants:

  • Can be given meaningful names. Rather than use a cryptic value such as 0.00888759, you can use a meaningful name such as YEN_TO_DOLLARS_EXCHANGE_RATE.

  • Are easy to modify. If the exchange rate changes, you have to modify only the single statement where the value of the constant is defined.

  • Are less prone to typing mistakes because the value (which might be something along the lines of 0.00888759) has to be entered only once. In addition, constants must be predefined the same way variables are predeclared. If you use the Option Explicit statement in VBScript, any mistyped constant name will generate an error.

  • Cannot be changed, inadvertently or otherwise. After a constant has been defined, any attempt by the script to change its value will generate an error.

  • Are useful for string values as well as for numeric values. For example, suppose you have a standard message that is repeatedly echoed to users when a script runs. Rather than type the message multiple times, define it once as a constant. If you need to change the message, you need to change it only in one location.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft