Sometimes you need a value that never changes. The speed of light. The number of days in a week. The value of PI. These are constants — fixed values that your program should not modify.
C gives you two ways to create constants.
The const Keyword
You can declare a variable as const. This tells the compiler the value will not change. If you try to change it, the compiler will give you an error.
const int DAYS_IN_WEEK = 7;
const float PI = 3.14159;
The #define Directive
The #define preprocessor directive creates a macro — a name that gets replaced with its value before compilation. No semicolon needed. By convention, constants are written in UPPERCASE.
#define MAX_STUDENTS 30
#define PI 3.14159
Literal Constants
Sometimes you just write the value directly. These are literal constants. The number 5 in your code is a literal. So is the string "Hello" and the character 'X'.
#include
#define TAX_RATE 0.08
int main() {
const int BASE_PRICE = 100;
float total = BASE_PRICE + (BASE_PRICE * TAX_RATE);
printf("Base price: $%d\n", BASE_PRICE);
printf("Total with tax: $%.2f\n", total);
return 0;
}
Try it Yourself →