Constants in C Programming
What is a Constant
A constant is a value that cannot be modified or changed once it has been set.
Constants are also sometimes referred to as literals. They are often used to represent values that are used many times throughout a program, such as the value of pi or the conversion factor between inches and centimeters.
const
keyword is used to define a constant in C.
For example:
const double PI = 3.14159;
const double CONVERSION_FACTOR = 2.54;
An alternate way to declare constant variable is using #define
.
For Example:
#define PI 3.14159
#define CONVERSION_FACTOR 2.54
Example of using Constant
Following is the example of using constants defined with the const
keyword in a C program:
#include <stdio.h>
int main(void) {
const double PI = 3.14159;
const double CONVERSION_FACTOR = 2.54;
double radius = 5;
double circumference = 0.0;
double diameter = 0.0;
circumference = 2 * PI * radius;
diameter = 2 * radius;
printf("The circumference of the circle is %lf.\n", circumference);
printf("The diameter of the circle is %lf.\n", diameter);
return 0;
}
Output:
Explanation:
- This program prompts the user to enter the radius of a circle.
- It then calculates and prints the circumference and diameter of the circle using the constants
PI
andCONVERSION_FACTOR
.
Output:
The circumference of the circle is 31.415900.
The diameter of the circle is 10.000000.
If the user entered a radius of 5, the program calculated the circumference to be 31.415900 and the diameter will be 10.000000.
Best Practices
Following are some of the best practices to follow when defining constants in C:
Use all uppercase letters and underscores to name constants. This helps to distinguish constants from variables and functions, and makes the code easier to read.
Give constants descriptive names that reflect their purpose. This will make the code easier to understand and maintain.
Avoid using const for values that are likely to change, such as configuration parameters or user-specific settings.
Use const for values that are used frequently throughout the program, such as mathematical constants or conversion factors. This will improve the performance of the program, as the constant values will be stored in memory and can be accessed quickly.
Use const
instead of #define
whenever possible. const
is more type-safe and easier to debug than #define
, as the type of the constant is explicitly specified.