teach-ict.com logo

THE education site for computer science and ICT

3. Constant

We have discussed variables. But what if the variable never changes from its initial value? In this case the variable is actually a 'constant'

A constant is a named item or symbol that does not change its initial value.

Constants are very useful in programming as they make source code easier to understand. Also should you need to change the value of a constant in the future, you only need to do it in one place within the program.

Example 1

For instance, let's define a constant called PI and set its value to 3.14. Now you can use PI as a substitute for the value in other lines of source code, like this

#define PI = 3.14



CircleLength = 2 * PI * radius

The second line of source code is easier to understand because PI is a well known mathematical constant. If in the future this particular software needs to do more accurate calculations, you change to value of PI to have more decimal places, like this

Declare PI = 3.14159265
  

And no need to change any other line of code.

 

Example 2

A constant does not have to be a numeric value. It could be other values such as a string, like this.

OUR_SITE_NAME = "Teach-ICT.com"

Now whenever the company name needs to appear, such as on a printout or screen, the constant OUR_SITE_NAME is used.

 

Declaring a constant

There is no standard way of declaring a constant. Each language has its own way of doing it. For instance in 'C' the key word #define is used to declare a constant, like this

#define OUR_SITE_NAME = "Teach-ICT.com"

When the compiler comes across the #define keyword, it understands that the symbol is a constant rather than a variable.

The debugging tool will usually spot the error when you try to change the value of a constant in the source code.

Naming a constant

Just as with variables you can use almost any name for a constant. But a very common approach to naming constants is to use CAPITAL LETTERS. It just makes it easier to see in the source code where a constant is in use rather than a variable. For instance

OUR_SITE_NAME = "Teach-ICT.com"
my_message = "Hello "
print (my_message, OUR_SITE_NAME)

In this case a constant and a variable has been declared and these are passed to a print routine in the third line. The constant stands out.

 

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: Using constants