In C, the #define directive is used to define constants using preprocessor directives. Constants defined using #define are known as macro constants. They are simple text substitutions performed by the preprocessor before the actual compilation of the code. Here's how constants are defined using the #define directive:
#define CONSTANT_NAME constant_value
Let's break down the process of defining constants using #define:
-
The #define directive is used at the global level of the program, typically placed at the beginning of the code before any function definitions.
-
CONSTANT_NAME represents the name you want to assign to the constant. It should be written in uppercase letters by convention to differentiate it from variables.
-
constant_value represents the value you want to assign to the constant. It can be any valid C expression or literal value.
-
There is no need to specify a data type for the constant because it is not a variable declaration. The constant will be replaced with its value during preprocessing.
Here's an example to illustrate the usage of #define directive:
#include <stdio.h>
#define PI 3.14159
#define MAX_VALUE 100
int main() {
float radius = 5.0;
int limit = MAX_VALUE;
float circumference = 2 * PI * radius;
printf("Circumference: %.2f\n", circumference);
printf("Maximum Value: %d\n", limit);
return 0;
}
Output:
Circumference: 31.42
Maximum Value: 100
In the above code, we define two constants using the #define directive. PI is assigned the value 3.14159, and MAX_VALUE is assigned the value 100. These constants are then used in the main function to calculate the circumference of a circle and set the limit value.
During preprocessing, the preprocessor replaces the occurrences of PI and MAX_VALUE with their respective values before the code is compiled. This substitution makes the code more readable and reduces the chances of errors caused by mistyping or accidental modifications of constant values.
It's important to note that #define constants do not occupy any memory since they are not variables. They are replaced by their values directly during preprocessing, saving memory and improving performance.