Got it! This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
A constant is not just something that "does not change".
4. Mathematics
A constant is a named literal
In mathematics, a constant is a number that does not change.
π or pi is 3.1415.,., the ratio of the circumference to the diameter of a circle.
e is the exponential constant 2.71828..., the number whose function derivative is itself (a fixed point).
... and so on ...
5. Physics
In physics, a constant as a number that is assumed not to change.
speed of light
Planck's constant
... and so on ...
6. Computer science
In computer science, a constant is a named literal.
Since literals do not change while a program is running, neither do constants. Change the literal (outside the running of the program) and the constant changes.
7. Read-only variables
One can think of a computer science constant as a variable whose value is not allowed to change (during the running of the program). That is, the variable is read-only.
8. Pseudo-constants
A pseudo constant is a variable that is used by the programmer to act as a constant. However, since the pseudo constant is actually a variable, it can be changed which could cause problems in the program.
A literal value cannot be simplified, although the value it represents may be represented in another way.
Since a constant names a literal, the value of a constant cannot be changed within a program, as the value of a literal cannot be changed.
Good programming style dictates that constants be used to avoid repeated literals with similar meanings. Such literals are often called magic literals.
Even if a magic literal appears only once, it is good programming practice to use a constant in place of the literal.
9. Example
A literal is an expressly written entity that represents a value.
The literal 6.0 represents the (abstract) value of six. For example, a state tax rate.
A constant is a named literal.
The constant salesTax could be used in place of the literal 6.0.
10. Constant example code
A constant is used just like a variable except that the value of a constant never changes during program execution.
Here is the C code.
Here is the output of the C code.
11. Constant assignment error
Trying to assign a constant results in an error since the value is read-only.
Here is the C code.
Here is the error text of the C code.
12. Pi
In the math.h library, the constant M_PI is defined as follows. It is not actually a constant, but a defined literal.
In this case, a define directive is used to create the constant, as if you had typed the value of pi at each and every place where it is used in the program.