C Constants
A constant in C is a value that should not change while the program runs. Constants help you give important fixed values clear names, such as a maximum score, tax rate, or number of days in a week.
Using const
The most common beginner-friendly way to create a named constant is to add const before a variable declaration. This tells the compiler that the value should stay the same after it is initialized.
#include <stdio.h>
int main(void)
{
const int days_in_week = 7;
printf("There are %d days in a week.\n", days_in_week);
return 0;
}
Output:
There are 7 days in a week.
The constant days_in_week is initialized with 7. After that line, assigning a new value to days_in_week would be an error because it was declared with const.
Constants Make Code Clearer
A named constant is often easier to understand than a number written directly inside a calculation. A number like 60 may be correct, but the name minutes_per_hour explains what the value means.
#include <stdio.h>
int main(void)
{
const int minutes_per_hour = 60;
int hours = 3;
int total_minutes = hours * minutes_per_hour;
printf("Hours: %d\n", hours);
printf("Minutes: %d\n", total_minutes);
return 0;
}
Output:
Hours: 3
Minutes: 180
Here, minutes_per_hour makes the multiplication easier to read. If the same fixed value is used in several places, a named constant also helps avoid repeated unexplained numbers.
Literal Constants
C also has literal constants, which are fixed values written directly in source code. Examples include 42, 3.14, 'A', and string text such as "Hello".
| Literal | Meaning |
|---|---|
100 |
An integer constant |
2.5 |
A decimal constant, usually treated as double |
2.5f |
A float constant because of the f suffix |
'Y' |
A character constant |
"Yes" |
A string literal |
Literal constants are useful, but names are better when the value has a special meaning in your program.
Using #define
C also supports constants created with the preprocessor directive #define. A #define name is replaced before the compiler checks the program.
#include <stdio.h>
#define MAX_SCORE 100
int main(void)
{
int score = 86;
printf("Score: %d out of %d\n", score, MAX_SCORE);
return 0;
}
Output:
Score: 86 out of 100
Many C programs write #define constants in uppercase, such as MAX_SCORE. For simple typed values inside functions, prefer const because it gives the compiler type information.
Common Beginner Mistakes
- Initialize a
constvariable when you declare it. - Do not try to assign a new value to a
constvariable later. - Use descriptive names for values with meaning, such as
seconds_per_minute. - Remember that
#definelines do not end with a semicolon.
The key idea is that constants give fixed values a clear, protected name. Next, you will learn how operators let you calculate, compare, and combine values.
