How to define constants in the C language?
In C language, constants can be defined using the #define or const keyword.
- Give a definition for
#define PI 3.14159
#define MAX_VALUE 100
In the example above, both PI and MAX_VALUE are defined as constants and can be used anywhere in the program.
- constant
const double PI = 3.14159;
const int MAX_VALUE = 100;
In the example above, both PI and MAX_VALUE are defined as constants, with their values determined at compile time and cannot be changed during program execution.
The difference between these two methods lies in:
- #define is a preprocessor directive that performs text replacement at compile time without type checking, while const is a variable declaration that undergoes type checking and memory allocation.
- Constants defined using #define do not have the concept of scope and can be used anywhere in the program. On the other hand, constants defined using const have scope and need to be accessed by their variable name.
It is recommended to use the const keyword to define constants, as it provides better type checking and scope control.