Multiline macros in C

In C programming, multiline macros allow you to define complex operations that span multiple lines. Unlike single-line macros, each line in a multiline macro must be terminated with a backslash '' character to indicate line continuation. When using multiline macros, it's recommended to enclose the entire macro definition in parentheses to avoid potential syntax errors.

Syntax

#define MACRO_NAME(parameters) ({\
    statement1;\
    statement2;\
    statement3;\
})

Example 1: Basic Multiline Macro

Here's an example demonstrating how to create and use a multiline macro for printing formatted output −

#include <stdio.h>

#define PRINT(x, str) ({\
    printf("The number %d", x);\
    printf(" is ");\
    printf(#str);\
    printf("<br>");\
})

int main() {
    int x = 10;
    if(x % 2 == 0) {
        PRINT(x, EVEN);
    } else {
        PRINT(x, ODD);
    }
    return 0;
}
The number 10 is EVEN

Example 2: Multiline Macro with Multiple Operations

This example shows a more complex multiline macro that performs multiple calculations −

#include <stdio.h>

#define MATH_OPERATIONS(a, b) ({\
    printf("Addition: %d + %d = %d<br>", a, b, a + b);\
    printf("Subtraction: %d - %d = %d<br>", a, b, a - b);\
    printf("Multiplication: %d * %d = %d<br>", a, b, a * b);\
    if(b != 0) {\
        printf("Division: %d / %d = %.2f<br>", a, b, (float)a / b);\
    }\
})

int main() {
    int num1 = 20, num2 = 4;
    printf("Mathematical operations for %d and %d:<br>", num1, num2);
    MATH_OPERATIONS(num1, num2);
    return 0;
}
Mathematical operations for 20 and 4:
Addition: 20 + 4 = 24
Subtraction: 20 - 4 = 16
Multiplication: 20 * 4 = 80
Division: 20 / 4 = 5.00

Key Points

  • Each line except the last must end with a backslash '' for line continuation
  • Use parentheses to enclose the entire macro definition to avoid syntax errors
  • The stringizing operator '#' converts macro parameters to string literals
  • Avoid trailing spaces after backslashes as they may cause compilation errors

Conclusion

Multiline macros in C provide a powerful way to create reusable code blocks. By following proper syntax with backslashes and parentheses, you can create efficient macros that enhance code readability and maintainability.

Updated on: 2026-03-15T10:28:30+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements