A Macro is a fragment of code which has been given a name. In C, macros are handled by the Preprocessor before the actual compilation begins. They allow you to define constants or create "pseudo-functions" that can make your code more readable and easier to maintain.
The most common way to create a macro is using the #define directive. Macros do not occupy memory like variables; instead, the preprocessor performs a "search and replace" throughout your source code.
PI or MAX_BUFFER_SIZE).You can define macros that take arguments, similar to functions. These are often faster than regular functions because there is no "function call overhead"—the code is injected directly into the call site.
The C compiler provides several standard macros that can be incredibly useful for debugging and logging.
| Macro | Description |
|---|---|
__DATE__ |
The current date as a string (MMM DD YYYY). |
__FILE__ |
The name of the current source file. |
__LINE__ |
The current line number in the source code. |
Macros are often used with #ifdef and #ifndef to include or exclude parts of the code based on certain conditions (e.g., different code for Windows vs. Linux).
When using function-like macros, always wrap arguments in parentheses. Failing to do so can lead to unexpected results due to operator precedence.