Constants which are also called Literals are referred to as fixed or definite values in a program that may not alter. it can exist as any data type and can be divided into Floating-Point Numerals, Integer Numerals, Strings, Boolean Values, and Characters. However, they can be used the way regular variables are used in a program, except that their values cannot be modified after being defined.
The syntax below shows to use the #define preprocessor to define a constant.
Syntax:
#define identifier value
Example:
#include <iostream.h>
#define PI 3.14
#define NEWLINE 'n'
int main()
{
int radius = 10;
float area;
area = PI * radius * radius; //area = PI r2
cout << "Radius of Circle: " << radius;
cout << NEWLINE;
cout << "Area of Circle: " << area;
return 0;
}
If you compiled and execute the code above, you will get the following result:
The syntax below shows to use of the const prefix to define a constant.
Syntax:
const type variable = value;
Example:
#include <iostream.h>
int main()
{
const float PI = 3.14;
const char NEWLINE = 'n';
int radius = 10;
float area;
area = PI * radius * radius;
cout << "Radius of Circle: " << radius;
cout << NEWLINE;
cout << "Area of Circle: " << area;
return 0;
}
If you compiled and execute the code above, you will get the following result: