The C Preprocessor is not part of the compiler itself, but rather a separate step that happens before compilation. It processes directives (commands starting with #) to include files, conditionally compile code, and define Macros.
A Macro is a fragment of code that has been given a name. Whenever the name is used, it is replaced by the contents of the macro.
The most common use of #define is to create named constants. This makes your code highly readable and easy to modify.
#include <stdio.h>#define PI 3.14159 #define MAX_USERS 100
int main() { double radius = 5.0; double area = PI * radius * radius; printf("Max users allowed: %d\n", MAX_USERS); printf("Area of circle: %.2f\n", area); return 0; }
Macros can also take arguments, similar to functions. However, they do not have the overhead of a function call (like pushing variables to the stack). The preprocessor simply replaces the text inline.
#include <stdio.h>// A macro to find the minimum of two numbers #define MIN(a, b) ((a) < (b) ? (a) : (b))
int main() { int x = 10, y = 20; printf("The minimum is: %d\n", MIN(x, y)); return 0; }
Pro Tip: Always wrap macro arguments in parentheses (like (a)) to prevent unexpected operator precedence issues when expressions are passed into the macro!
ANSI C defines several standard macros that you can use anywhere in your code, which are extremely useful for debugging and logging.
__FILE__: The current filename as a string.__LINE__: The current line number as an integer.__DATE__: The current date as a string.__TIME__: The current time as a string.Which preprocessor directive is used to define a macro in C?