Constants in C
A constant is a fixed value that cannot be changed during the execution of a program. It is also called a read-only value. Constants must be initialized at the time of declaration; otherwise, they may hold garbage values.Ways to Define Constants
1. Using the const keyword
2. Using #define (Preprocessor Macro)
Examples
Usingconst:
#define:
Value of PI: 3.14
Attempting to Change a Constant
const vs #define
| Feature | const | #define |
|---|---|---|
| Handled by | Compiler | Preprocessor |
| Memory allocated | Yes | No |
| Type safety | Enforced | Not enforced |
| Scope | Follows block rules | File-wide only |
| Error checking | Compile-time | None |
| Debugging | Easier — has a name | Harder — replaced before compiling |
const over #define for typed constants in modern C. Use #define for values that are truly compile-time substitutions (like include guards).