In the previous topic, we learned about variables, whose values can change during program execution.
But what if we want to store a value that should not change?
That's where constants come in.
What is a Constant?
A constant is a value that cannot be changed during the execution of a program.
For example, if we want to store the value of Pi:
const float PI = 3.14159;
Here, PI is a constant. We should not change its value later.
Think of it like a locked box:
PI
┌────────┐
│ 3.14159│ 🔒
└────────┘
The value is stored, but it cannot be modified.
Creating Constants Using const
The most common way to create a constant is by using the const keyword.
const int DAYS = 7;
Now if we try:
DAYS = 10;
the compiler will report an error because DAYS is a constant.
Variable vs Constant
The main difference is simple:
Variable | Constant |
|---|---|
Value can change | Value cannot be changed |
|
|
Used for changing data | Used for fixed data |
For example:
int age = 20;
age = 21; // Allowed
const int DAYS = 7;
DAYS = 10; // Not allowed
Constants Using #define
C also allows us to create constants using #define.
#define PI 3.14159
Now we can use PI in our program:
printf("%f", PI);
Unlike const, #define is handled by the preprocessor before the actual compilation of the C program.
For beginners, just remember that both approaches can be used to represent fixed values.
Why Use Constants?
Constants are useful when a value should remain fixed throughout the program.
For example:
const int MAX_MARKS = 100;
const float PI = 3.14159;
This makes the program easier to understand and prevents accidental changes to important values.
In Simple Words
A variable stores a value that can change, while a constant stores a value that should remain fixed.
For example, a student's marks can change, but the maximum marks might always be 100.