C Constants: A Beginner’s Guide
In C programming, constants are fixed values that do not change during the execution of a program. They make your code more readable, more secure, and easier to maintain.
Why Use Constants?
Prevent accidental modification of values
Make code more meaningful (e.g., PI
instead of 3.14
)
Improve readability and maintainability
Types of Constants in C
Literal Constants
These are actual fixed values like:
10, 3.14, 'A', "Hello"
Symbolic Constants
Created using either:
#define
const
keyword
Using #define to Declare Constants
const int MAX = 100;
Has a data type
Can be used in functions or globally
Compiler prevents modification
Example:
#include <stdio.h>
int main() {
const int maxUsers = 50;
printf("Max Users: %d\n", maxUsers);
// maxUsers = 100; // ❌ Error: cannot modify a const variable
return 0;
}
Differences Between #define and const
Feature | #define | const |
---|---|---|
Data Type | No | Yes |
Scope | Global | Respect C scope rules |
Compiler Check | No | Yes |
Debugging Help | Limited | More accurate error info |
Best Practices for Constants
Use UPPERCASE for constant names (e.g., MAX_LIMIT
)
Use const
when a data type or scope is needed
Group all constants at the top of your file
Avoid using magic numbers (e.g., use PI
instead of 3.14
directly)
Common Mistakes to Avoid
Mistake | Fix |
---|---|
Modifying a const variable | Remove modification or use a non-const |
Using undeclared constants | Declare before use |
Using wrong data type with const | Match the type to the intended value |