Constants

Constants or literals refer to fixed values that the program may not alter after they have been defined.  Constants can be of any basic data type such as an integer or character.

 C has two types of constants:

  • Literal Constants
  • Symbolic Constants 

Literal Constants

A literal constant is a hard code value that is typed directly into the source code such as a number, character, or string that may be assigned to a variable or symbolic constant.

Symbolic Constants

A symbolic constant is an identifier representing a constant value.  Whenever a constant value is required the constant name can be used in place of that value throughout the program thus the value of the symbolic constant only needs to be entered when it is first defined. Symbolic constants can be defined using the preprocessor directive #DEFINE or the const keyword.

Defining Constants Using #define - The #define directive enables a simple text substitution that replaces every instance of the name in the code with a specified value with the compiler only seeing the final result.  Since these constants don't specify a type, the compiler cannot ensure that the constant has a proper value and their use is discouraged. The prototype of a define directive is -

#define PI 3.14

In the above example, every incidence of the constant directive PI will be replaced by 3.14

Defining Constants with the const Keyword prefix -  Variables declared const can’t be modified when the program is executed. A value is initialised at the time of declaration and is then prohibited from being changed. 

In the code sample below the value, PI is declared as both a const variable and a preprocessor directive

#define PI 3.14 //set value of constant directive
int main()
{
const float PIVALUE= 22.0 / 7; //set value of constant
printf( "\nValue of constand variable PI %f", PIVALUE);
printf( "\nValue of constant directive PI %f", PI);
return 0;
}

Constants are often fully capitalised by programmers to make them distinct from variables. This is not a requirement but the capitalisation of a constant must be consistent in any statement since all variables are case sensitive.