Send Close Add comments: (status displays here)
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.
C: Constants


1. C: Constants

2. C: Constants

3. Constants
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.

5. Physics
In physics, a constant as a number that is assumed not to change.

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. A constant is a named literal.

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.
#define M_PI 3.14159265358979323846264338327950288

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.

13. End of page

14. Multiple choice questions for this page