In C, both #define and const define constant values, but these constants differ greatly in their behaviors and implementation. #define is a preprocessor directive used to define constants that are replaced by their value during preprocessing, before actual compilation begins. while const defines a typed constant with type safety.
The below table lists the primary differences between the constants defined using #define and using const keyword:
| Aspect | #define | const |
|---|---|---|
| Type Safety | No type checking is performed and the constant defined acts as a literal. | Enforces type checking on the constant. |
| Memory | Does not allocate memory for constant. | Allocates memory for storage of constant. |
| Scope | Its scope is global so it is available throughout the program. | Follows block or function scope. |
| Debugging | Hard to debug as it is replaced during preprocessing. | Easier to debug as it retains variable properties. |
| Modifiers | Cannot use modifiers with it like static | Can use modifiers with it (e.g., static) |
| Evaluation | Evaluated at preprocessing. | Evaluated at runtime. |
| Usage | It is preferred for macros or constants without type. | It is preferred for typed constants |
#define in C
#define in C is a preprocessor directive that replaces a name with a specific value before compilation. It works like a shortcut, where the preprocessor substitutes the defined name with the value, and it doesn't have a type like regular variables.
Example:
#include <stdio.h>
// Define constant PI
#define PI 3.14
int main() {
printf("PI = %f\n", PI);
return 0;
}
Output
PI = 3.140000
Explanation: Here, #define is used to define a constant PI. The preprocessor replaces PI with 3.14 before compilation, and the program behaves as if the literal value 3.14 was written directly in place of PI.
When to Use #define?
The use of #define is prefferend in the following cases:
- Constants that do not require a specific type.
- Simple text replacement or macros.
- Avoiding additional memory allocation.
const in C
The const keyword is used to define constants with a specific type. Unlike #define, which is handled by the preprocessor, const is part of the C language and the compiler checks for type safety. A const variable behaves like any other variable, except its value cannot be modified after initialization.
#include <stdio.h>
// Define constant PI
const float PI = 3.14;
int main() {
printf("PI = %f\n", PI);
return 0;
}
Output
PI = 3.140000
Explanation: In this case, const is used to define a constant PI with type float. The compiler ensures type safety, and the value of PI cannot be changed after it is initialized.
When to Use const?
Use const for:
- Typed constants that benefit from type checking.
- Constants with a defined scope.
- Improved readability and debugging.