A symbolic constant can be defined as a constant that is represented by a name (symbol) in a program. Like a literal constant, a symbolic constant cannot undergo changes. Whenever the constant’s value is needed in the program, the name of the constant is used in the same way as the name of a variable is used to access its value.
There are two methods in C for defining a symbolic constant:
- Using the
#define
directive - Using the
const
keyword
We know that PI is a constant with value 3.1416 and it is defined in C by using the const
keyword in the following way:
const float PI = 3.1416; /* defining PI as a constant */
Here, since we’ve defined PI as a const
, any subsequent attempts to write or modify the value of PI are not allowed in the entire program.
const float PI = 3.1416;
PI = 300; /* This is an error. const cannot be manipulated. */
The following code segment illustrates the use of symbolic constant (defined by using #define
directive) in a C program:
#define PI 3.1416 /* PI has been defined as a symbolic constant in this line */
... other lines of code ...
area = PI * (radius) * (radius);
... other lines of code ...
The following program shows the use of symbolic constant to compute the area of a circle:
/* A program to compute the area of a circle */
#include
#define PI 3.1416
int main() {
float area, radius;
printf("Enter the radius of the circle:");
scanf("%f", &radius);
area = PI * radius * radius;
printf("\n The area of the circle with radius %f is: %f", radius, area);
return 0;
}
The output of the program is:
Enter the radius of the circle:3
The area of the circle with radius 3.000000 is:29.608951
Let us see another program to depict the use of symbolic constant to compute the area and circumference of a circle.
/* A program to compute the area and circumference of a circle */
#include
int main() {
float area, circumference, radius;
const float PI = 3.1416;
printf("Enter the radius of the circle:");
scanf("%f", &radius);
area = PI * radius * radius;
circumference = 2 * PI * radius;
printf("\n The area and circumference of the circle with radius %f are: %f and %f respectively.", radius, area, circumference);
return 0;
}
The output of the program is:
Enter the radius of the circle:5
The area and circumference of the circle with radius 5.000000 are: 78.540001 and 31.415998 respectively.