In C programming, variables and constants are both used to represent and work with values in a program. However, the main difference between them is whether their values can be changed during program execution.
A variable is a named memory location used to store a value that can be changed during the execution of a program. The value stored in a variable can be modified whenever required, provided that the new value is compatible with the variable's data type.
For example:
int marks = 75;
marks = 85;
In this example, marks is a variable. Initially, it contains
75, but its value is later changed to 85.
A constant is a value that is not intended to be changed during the execution of a program. Once a constant is defined or given its value, that value remains fixed.
In C, a constant can be created using the const keyword. For
example:
const float PI = 3.14159;
Here, PI represents a constant value. Attempting to change its
value later in the program is not allowed:
PI = 3.14; // Invalid
| Variable | Constant |
|---|---|
| Its value can be changed during program execution. | Its value cannot be changed after it has been defined. |
| It is used when a value needs to change. | It is used when a value must remain fixed. |
Example: int age = 20; |
Example: const int MAX = 100; |
| It can normally be assigned a new value. | It cannot normally be assigned a new value. |
#include
int main()
{
int salary = 30000;
const int WORKING_HOURS = 8;
salary = 35000;
printf("Salary = %d\n", salary);
printf("Working Hours = %d\n", WORKING_HOURS);
return 0;
}
In this example, salary is a variable because its value can be
changed from 30000 to 35000. On the other hand,
WORKING_HOURS is declared as a constant using the
const keyword, so its value should not be modified.
Constants are particularly useful when a program repeatedly uses a value
that should remain unchanged. For example, instead of repeatedly writing
3.14159 when performing calculations involving the mathematical
constant pi, we can define it once and use a meaningful name such as
PI.
const float PI = 3.14159;
This makes the program easier to read, understand, maintain, and modify. It also reduces the possibility of accidentally changing an important fixed value.
The easiest way to remember the difference is:
Variable = A named value that can change.
Constant = A named value that remains fixed.
Therefore, if a program needs a value that may change during execution, a variable is appropriate. If a value should remain fixed, a constant should be used.