How to write multiline macro in C language?

Quick links

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 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>