C Constants: Understanding Your Fixed Values
In C programming, constants are fixed values that cannot be changed during the program's execution. They play a vital role in maintaining code clarity, preventing accidental modifications, and improving program efficiency.
This will declare the variable as "constant", which means unchangeable and read-only:
Example
#include <stdio.h>
int main() {
const int myNum = 15;
myNum = 10;
printf("%d", myNum);
return 0;
}
Output
prog.c: In function 'main':
prog.c: error: assignment of read-only variable 'myNum'
Declare Variables as Constants When Values Are Unlikely to Change: A Example
Example
#include <stdio.h>
int main() {
const int minutesPerHour = 60;
const float PI = 3.14;
printf("%d\n", minutesPerHour);
printf("%f\n", PI);
return 0;
}
Output
60
3.140000
Notes On Constants
When you declare a constant variable in most programming languages, it must be assigned a value at the time of declaration. Here's why:
Example
#include <stdio.h>
int main() {
const int minutesPerHour;
minutesPerHour = 60;
printf("%d", minutesPerHour);
return 0;
}
Output
prog.c: In function 'main':
prog.c:5:18: error: assignment of read-only variable 'minutesPerHour'
5 | minutesPerHour = 60;
Good Practice
Here are some good headings for the topic of declaring constant variables with uppercase in different contexts.
It is not required, but useful for code readability and common for C programmers:
Example
#include <stdio.h>
int main() {
const int BIRTHYEAR = 1980;
printf("%d", BIRTHYEAR);
return 0;
}
Output
1980