Constants in C
A constant is a value that cannot be changed after it is set. Constants make programs safer (prevent accidental modifications) and more readable.
Method 1: #define Preprocessor Macro
c
#include <stdio.h>
// Constants defined before main()
#define PI 3.14159265
#define MAX_MARKS 100
#define PASS_MARKS 40
#define SCHOOL_NAME "CodeKaFunda"
int main() {
float radius = 5.0;
float area = PI * radius * radius;
printf("School : %s\n", SCHOOL_NAME);
printf("PI : %.5f\n", PI);
printf("Area : %.2f\n", area); // 78.54
printf("Max : %d\n", MAX_MARKS);
printf("Pass : %d\n", PASS_MARKS);
return 0;
}▶ Output
School : CodeKaFunda PI : 3.14159 Area : 78.54 Max : 100 Pass : 40
Method 2: const Keyword
c
#include <stdio.h>
int main() {
const int PASSING_MARKS = 40;
const float TAX_RATE = 0.18f; // 18% GST
const char GRADE = 'A';
int marks = 85;
float price = 1000.0f;
float tax = price * TAX_RATE;
printf("Price : Rs. %.2f\n", price);
printf("GST (18%%) : Rs. %.2f\n", tax);
printf("Total : Rs. %.2f\n", price + tax);
if (marks >= PASSING_MARKS)
printf("Result: PASS with Grade %c\n", GRADE);
// ERROR: cannot modify a const!
// PASSING_MARKS = 35; // This would cause compile error
return 0;
}▶ Output
Price : Rs. 1000.00 GST (18%) : Rs. 180.00 Total : Rs. 1180.00 Result: PASS with Grade A
#define vs const — Which to Use?
| Feature | #define | const |
|---|---|---|
| Type safety | No type — just text substitution | Has a specific type (int, float...) |
| Memory | No memory allocated | Memory is allocated |
| Debugging | Harder (preprocessor replaces before compile) | Easier to see in debugger |
| Scope | Global (file-wide) | Can be local or global |
| Best use | String constants, mathematical constants | Typed numeric constants |
📌 Note: Convention: Use ALL UPPERCASE for constants —
MAX_SIZE, PI, TAX_RATE — so they stand out from variables.