C Constants
A constant is a value that cannot change once it's set. In C you can create constants using the const keyword or with the #define preprocessor directive.
Using constants instead of hardcoded 'magic numbers' scattered through your code makes programs easier to read, maintain and update.
const type NAME = value;
#define NAME valueconst keyword
Placing const before a type declaration makes that variable read-only after initialization. Any attempt to reassign it causes a compile error.
#define macro
#define creates a preprocessor macro that textually replaces every occurrence of the name with its value before compilation, and does not use memory like a variable.
#include <stdio.h>
int main() {
const float PI = 3.14159f;
printf("%.2f\n", PI);
return 0;
}3.14PI is declared as a const, so it cannot be changed later in the program.
#include <stdio.h>
#define MAX 100
int main() {
printf("Max is %d\n", MAX);
return 0;
}Max is 100#define MAX 100 replaces every occurrence of MAX with 100 before compiling.
Key points
- const makes a typed variable read-only.
- #define creates a preprocessor text-substitution macro.
- Constants improve readability and prevent accidental changes.
- By convention, macro constants are written in UPPERCASE.
