Constants or literals refer to fixed values that the program may not alter after they have been defined. Constants can be of any of the basic data types such as an integer or character.
C has two types of constants:
A literal constant is a 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. For instance, in the variable declaration count=10, the variable count is assigned the literal constant 10.
A symbolic constant is an identifier that represents a constant value for the life of the program. 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 only the final result. Since these constants don't specify a type, the compiler cannot ensure that the constant has a proper value so it’s better to use the standard constant method. The practice of defining constants using the preprocessor dates back to early versions of the C language. It is now deprecated and should not be used. 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 - simply involves declaring a variable with const prefix. Variables declared to be 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.
Last Updates:25 October 2022