What are constants in computer programming?

1 answer

Answer

1025878

2026-05-13 06:25

+ Follow

A constant may refer to a literal constant, a constant variable.

A literal constant is a value that we use to initialise or assign to a variable, literally, such as:

int x {42}; // initialise

x = 0; // assign

Here, the values 42 and 0 are literal constants.

A constant variable is a variable which will not change value after initialisation:

const int x {42}; // initialise

x = 69; // error - cannot assign to a constant variable

Constant variables are useful when we wish to use the same constant value repeatedly within a scope. We could also use a literal constant rather than a constant variable, however naming our constants makes it easier to refer to the value consistently, particularly during code maintenance where we may wish to review the value. With a constant variable we need only change the initialiser, but with literal constants we must change every occurrence of the literal and that can lead to inconsistencies. Consider the following:

int x[100];

int y[100];

for (int i=0; i<100; ++i) { cout << x[i] << endl; }

// ...

for (int i=0; i<100; ++i) { cout << y[i] << endl; }

Here we've used the literal constant 100 four times. At a future time we may decide array x really needs 200 elements rather than 100, but we have to be careful which literals we change because array y makes use of that same literal constant. Using constant variables helps keep those usages separate:

const int xmax {100};

const int ymax {100};

int x[xmax]; int y[ymax]; for (int i=0; i<xmax; ++i) { cout << x[i] << endl; } // ...

for (int i=0; i<ymax; ++i) { cout << y[i] << endl; }

Now we can safely change the xmax initialiser without affecting any usage of the ymax constant:

const int xmax {200};

const int ymax {100};

int x[xmax];

int y[ymax];

for (int i=0; i<xmax; ++i) { cout << x[i] << endl; }

// ...

for (int i=0; i<ymax; ++i) { cout << y[i] << endl; }

Note that a constant variable cannot be initialised by a non-constant variable:

int x {42};

const int y {x}; // error - x is non-constant

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.