In C Language, the #define directive is a preprocessor directive used to define macros.
Macros are essentially symbolic constants or code snippets that are replaced by their respective values or code during the preprocessing stage, before the actual compilation of the program.
This allows for more flexible and readable code.
#define identifier replacement
"identifier" is the name of the macro being defined.
"replacement" is the value or code snippet to be substituted whenever the macro is encountered in the code.
#define PI 3.14159
Note: Here, PI is defined as a macro with the value 3.14159. Whenever PI appears in the code, it will be replaced with 3.14159.
#define SQUARE(num) ((num) * (num))
Note: This macro calculates the square of a given number. When used like SQUARE(3), it expands to (3 * 3).
#define COUNT 3 #define USER_NAME "Alice Collin!"
Note: This macro defines a string "Alice Collin!". Whenever "USER_NAME" appears in the code, it will be replaced with "Alice Collin!" and the same for "count".
#define DEBUG
By defining "DEBUG", we can enable debugging code blocks conditionally using "#ifdef" or "#ifndef".
#ifdef DEBUG printf("Debugging information\n"); #endif
Note: This code block will be included in the final compiled program only if DEBUG is defined.
#define MAX(x, y) ((x) > (y) ? (x) : (y))
This macro defines a function-like macro MAX that takes two arguments and returns the maximum of the two. For example, MAX(12, 7) expands to ((12) > (7) ? (12) : (7)), which evaluates to 12
"#define" is a powerful tool in C programming that allows for code abstraction, making programs more readable and maintainable.
However, it should be used judiciously to avoid potential pitfalls such as unintended side effects and code bloat.