Constants and literals are ways of describing data that does not change while a program runs. For example, a statement in C such as
const float pi = 3.14159;
expresses a value that will be used in calculations, but not changed. Constants can be of any data type, including character strings as well as numbers. String constants are usually enclosed in single or double quotes:
char * Greeting = “Hello, World”;
Actual strings and numerals found in programs are some-times called literals, meaning that they are to be accepted exactly as given (literally) rather than standing for some other value. Thus 3.14159 and Hello, World as given above can be considered to be numeric and string literals respectively.
Because many languages consider a value of 1 as rep-resenting a “true” result for a branch or loop test, and 0 as representing “false,” programs in languages such as C often include declarations such as:
const True = 1; const False = 0;
This lets you later have a loop construction such as
while (True) {
’ body of program } ;
which is a more readable way to code an endless loop than:
while (1) {
’ body of program } ;
However languages such as Pascal and C++ have a special boolean data type (bool in C++) that allows for constants or variables that will have one of two values, true or false.
Some languages provide a way to set up an ordered group of constant values (see enumerations and sets).
Constants vs. Variables
The difference between a constant and a variable is that a variable represents a quantity that can change (and is often expected to). For example, in the statement
int Counter = 0;
Counter is set to a starting value of zero, but will presum-ably be increased as whatever is to be counted is counted.
Most compilers will issue an error message if they detect an attempt to change the value of a constant. Thus the sequence of statements:
const float Tax_Rate = 8.25; Tax_Rate = Tax_Rate + Surtax;
would be illegal, since Tax_Rate was declared as a constant rather than as a variable.
Many compilers, as part of code optimization, can discover values or expressions that will remain constant throughout the life of the program, even if they include variables. Such constants can be “propagated” or substi-tuted for variables. This can speed up execution because unlike a variable, a constant does not need to be retrieved from memory (see compiler).
No comments:
Post a Comment