Constant Declarations - Research Article from World of Computer Science

This encyclopedia article consists of approximately 1 page of information about Constant Declarations.
Encyclopedia Article

Constant Declarations - Research Article from World of Computer Science

This encyclopedia article consists of approximately 1 page of information about Constant Declarations.
This section contains 291 words
(approx. 1 page at 300 words per page)

Constant declarations create named constants. A constant is the opposite of a variable and has a value that once set never changes during the life of the program.

There are two types of constant: literal constants and declared constants. A literal constant is a hard-coded number or string in the program code. For example, in the code below, the variable "x" is assigned the value "3," where the "3" is actually a literal constant:

  • int x = 3;

A declaration gives an object a name, and in a typed language it will say what type it is. In contrast a definition gives the named symbol a value. Different languages have different syntax, but most allow the programmer to declare a constant and give it a name. Declaring a constant is usually very similar to declaring a variable in that it has a name and frequently a type and a value. The chief difference is that the constant has to be defined at the same time as it is declared, like this C/C++ constant, for example:

  • const int theAnswer = 42; // C and C++

If "theAnswer" were a variable it could be declared and then defined elsewhere; but a constant cannot be treated in this way because it is constant and is not allowed to change. It is an error to do this:

  • const int theAnswer = 42;
  • theAnswer = 43;

C and C++ use the "const" keyword to indicate that a named symbol is a constant, as in the examples above. Java has a identical semantics but uses the keyword "final" instead:

  • final int theAnswer = 42; // Java

Other languages like Ada and Smalltalk use different syntax altogether, but the principle remains: it is possible to declare named symbols that remain constant for the life of the program.

This section contains 291 words
(approx. 1 page at 300 words per page)
Copyrights
Gale
Constant Declarations from Gale. ©2005-2006 Thomson Gale, a part of the Thomson Corporation. All rights reserved.