Loading, please wait...

Constants

"Constant" Variables and the const Qualifier

A variable may be declared as constant using the const qualifier.

const double pi = 3.14159;
const int year_length = 365;

const int TRUE=1, FALSE=0;

Once declared, these variables cannot have any value assigned to them or be changed in any other way, but they can be used in expressions.

pi = 1.234; /* illegal */
diam = 2*pi*rad; /* valid */

y = year_length; /* valid */

year_length = 365; /* illegal */

It follows that const variables MUST be initialized to be of any use.

const variables are used to make a program more readable. They also make a program easier to maintain if the constant needs to be changed in later versions of the program. If the numeric value has been used the change may need to be made in many places in the code some of which could possibly be missed. The use of a const variable means that only one line needs to be changed to alter the constant value throughout the program.