Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.
Again, constants are treated just like regular variables except that their values cannot be modified after their definition.
#define
preprocessor.const
keyword.#define
preprocessor to define a constant:
#define identifier value
Following example explains it in detail:
#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;
}
When the above code is compiled and executed, it produces the following result:
const type variable = value;
Following example explains it in detail:
#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;
}
When the above code is compiled and executed, it produces the following result:
Ask Question