Constants in C
In C programming, a constant is a value that cannot be changed during the execution of a program.
Once a constant is defined, its value remains fixed throughout the program. This helps in writing safe, readable, and reliable code.
Why Constants Are Important
Constants are used when a value should never change. They help:
- Prevent accidental modification of important values
- Improve program readability
- Make maintenance easier
- Reduce logical errors
For example, values like PI (3.14), tax rates, or maximum limits should remain constant.
Types of Constants in C
C supports two main ways to define constants:
- Using the
constkeyword - Using
#definepreprocessor directive
1. Using const Keyword
The const keyword is used to declare variables
whose values cannot be changed after initialization.
const int MAX_AGE = 100;
If you try to change MAX_AGE later,
the compiler will generate an error.
MAX_AGE = 120; // Error: cannot modify a constant
2. Using #define Directive
The #define directive is used to create symbolic constants.
These constants do not occupy memory; they are replaced by the compiler before compilation.
#define PI 3.14
#define MAX_STUDENTS 60
Wherever PI appears in the program,
the compiler replaces it with 3.14.
Numerical Example Using Constants
Let us calculate the area of a circle using a constant.
#include <stdio.h>
#define PI 3.14
int main() {
float radius = 5;
float area;
area = PI * radius * radius;
printf("Area of circle = %.2f", area);
return 0;
}
Here, PI is a constant and should never be modified.
Difference Between const and #define
Although both are used for constants, they are different.
constuses memory and follows data types#definedoes not use memory and has no data typeconstprovides better type checking#defineis replaced during preprocessing
Real-World Thinking
Think of constants like:
- Maximum speed limit on a road
- Number of days in a week
- Fixed tax percentage
These values should not change during program execution.
Mini Practice
- Create a constant for the number of days in a week
- Create a constant for tax rate
- Use them in a simple calculation
Quick Quiz
Q1. What is a constant?
A constant is a value that cannot be changed during program execution.
Q2. Which keyword is used to create constants in C?
The const keyword is used to create constants.
Q3. Does #define use memory?
No, #define does not use memory.
Q4. Which provides better type safety: const or #define?
const provides better type safety.
Q5. Can the value of a constant be modified later?
No, constants cannot be modified after definition.