HOME HTML EDITOR C JAVA PHP

C Macros: The Power of Preprocessing

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.

1. The #define Directive

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.

2. Function-like Macros

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.

#include <stdio.h>

#define SQUARE(x) (x * x)
#define MAX(a, b) ((a) > (b) ? (a) : (b))

int main() {
    printf("Square of 5: %d\n", SQUARE(5));
    printf("Max of 10 and 20: %d\n", MAX(10, 20));
    return 0;
}

3. Predefined Macros

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.

4. Conditional Compilation

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).

#define DEBUG_MODE

#ifdef DEBUG_MODE
    printf("Debug: System initialized.\n");
#endif

5. The Importance of Parentheses

When using function-like macros, always wrap arguments in parentheses. Failing to do so can lead to unexpected results due to operator precedence.

// BAD MACRO
#define MULTIPLY(a, b) a * b
// Result of MULTIPLY(2+3, 4) is 2 + 3 * 4 = 14 (Wrong!)

// GOOD MACRO
#define MULTIPLY(a, b) ((a) * (b))
// Result of MULTIPLY(2+3, 4) is ((2+3) * (4)) = 20 (Correct!)

6. Macros vs. Const Variables

Pro Tip: Use #define for simple constants and conditional compilation, but prefer static inline functions for complex logic to get the benefit of type checking and better debugging!