How to write multiline macro in C language?

How to write multiline macro in C programming language. We generally define macros that spans over single line. However there exists situations when you want to define a macro that spans over multiple line.

In this post I will explain how to write a multiline macro in C language. So let us get started.

Required knowledge

Basic C programming, Preprocessor directives, Macros

During the course of macros programming exercises, we learnt basics of macros. How to define and undefine a macro. In this post we will continue ahead with macro and will learn to define multiline macro.

For most of the times macros are sweet and short, extended upto single line. However, sometimes we define complicated macros that spans over multiple lines. Defining those macros in single line will lose code readability, hence we define multiline macro .

To define a multiline macro append \slash at the end of each line of a macro.

Program to define multiline macro

/**
 * C program to create multiline macro
 */

#include <stdio.h>

// Macro to check and print even odd number
#define EVEN_ODD(num)               \
    if (num & 1)                    \
        printf("%d is odd\n", num); \
    else                            \
        printf("%d is even\n", num);

int main()
{
    int num;

    // Input number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    EVEN_ODD(num);

    return 0;
}
Note: Last line of macro must not contain \ symbol.

Output

Enter any number: 11
11 is odd

Happy coding ?‍?