Check if a Multi-lined macro is defined or not

Viewed 56

I know that for a single lined macro, we would simply use

#ifndef X
#define X 10
#endif

However I am attempting to do the same thing but with a multi-lined macro

#ifndef mallocErr(X)
#define mallocErr(X) \
    do { \
        if (X == NULL) { \
            perror("malloc"); \
            exit(EXIT_FAILURE); \
        } \
    } while (0) \
#endif

I'm sure my issue is that the syntax for #ifndef mallocErr(X) is incorrect, but I can't seem to find the proper format, or maybe I am approaching this the wrong way?

1 Answers

There are a few errors here.

  1. Do not include the macro's parameters when checking if the identifier is defined
  2. Do not escape the last newline for your #define
  3. Style: it's generally a good idea to enclose macro parameter expansions in parentheses in case an expression is supplied. e.g. use (X) instead of X

Addressing all these things produces:

#ifndef mallocErr
#define mallocErr(X) \
    do { \
        if ((X) == NULL) { \
            perror("malloc"); \
            exit(EXIT_FAILURE); \
        } \
    } while (0)
#endif

I would like to point out that there's nothing inherently special about a "multi-lined macro". All you are doing here is escaping just before the newline to prevent it from being evaluated. This is not unique to macro definitions.

For example, this is perfectly fine:

#include <stdio.h>
int main(void)
{
    printf("Hello, \
world!\n");
    return 0;
}

Or even:

#include <stdio.h>
int main(void)
{
    p\
r\
i\
n\
t\
f("Hello, world!\n");
    return 0;
}

Note that neither of the above examples are a good idea. I just wanted to illustrate that escaping the newline is a language feature that is not isolated to macros.

Related