Macros in C (#define)

Macros are preprocessor directives used to define constants, functions, or expressions before the compilation starts. A macro is replaced directly in the source code by the preprocessor, improving performance and reducing repeated code.

What is a Macro?

A macro is a rule or pattern that replaces specific text in your program before actual compilation. It is handled by the C Preprocessor.

Types of Macros

1. Object-like Macro

These macros represent a constant value.

#include <stdio.h>

#define PI 3.1415
#define MAX 100

int main() {
    printf("PI = %.4f\n", PI);
    printf("Max limit = %d", MAX);
    return 0;
}

2. Function-like Macro

Looks like a function but expands as text.

#include <stdio.h>

#define SQUARE(x) (x * x)

int main() {
    printf("Square of 6 = %d", SQUARE(6));
    return 0;
}

3. Parameterized Macro

Macros that accept multiple arguments.

#include <stdio.h>

#define ADD(a,b) (a + b)
#define MULT(a,b) (a * b)

int main() {
    printf("Add = %d\n", ADD(3,4));
    printf("Multiply = %d", MULT(3,4));
    return 0;
}

4. Multi-line Macro

Create a multi-statement macro using backslash ( \ ).

#include <stdio.h>

#define SHOW(x) \
    printf("Value = %d\n", x); \
    printf("Double = %d\n", x * 2);

int main() {
    SHOW(5);
    return 0;
}

5. Predefined Macros

C provides several built-in macros:

Example

#include <stdio.h>

int main() {
    printf("File: %s\n", __FILE__);
    printf("Line: %d\n", __LINE__);
    printf("Date: %s\n", __DATE__);
    printf("Time: %s\n", __TIME__);
    return 0;
}

When to Use Macros?

âš  NOTE: Macros do not follow scope rules. Once defined, they apply until #undef is used or the file ends.

Practice Questions

  1. What is a macro? Explain with examples.
  2. Differentiate object-like and function-like macros.
  3. Write a macro to calculate area of a triangle.
  4. Explain predefined macros.
  5. What are the advantages of using macros?

Practice Task

Write a macro SWAP(a, b) to swap two numbers without using a temporary variable.