Multiline #define madness

Like to write multi-line #define macros but don’t like how the slashes \\ spoil their look? With the next simple trick of using /* C-style comments */, you can achieve the same thing in a beautiful manner.

#include <stdio.h>
#define PRINT_TWICE(x) do { /*
                */ printf( /*
                */ "%s %s\n", /*
                */ (x), (x) /*
                */ ); } while (0)
int main() {
    PRINT_TWICE("Hello world!");
    return 0;
}

And it works!

[user@host ~]$ gcc multiline-madness.c
[user@host ~]$ ./a.out
Hello world! Hello world!

Notice how split pairs of /* and */ hide ends of lines from the preprocessor:

[user@host ~]$ gcc -E multiline-madness.c
...
int main() {
    do { printf( "%s %s\n", ("Hello world!"), ("Hello world!") ); } while (0);
    return 0;
}

Written by Grigory Rechistov in Uncategorized on 20.05.2020. Tags: define, macrodefines,


Copyright © 2024 Grigory Rechistov