David542
David542

Reputation: 110143

Example of using the ## preprocessor operator

I know the following is a very trivial example, but how would I convert the following into a single function call that uses the preprocessor ## 'glue' operator?

void print_string(char *s)
{
    printf("%s\n", s);
}
void print_num(int n)
{
    printf("%d\n", n);
}

int main(void)
{
    print_string("Hello");
    print_num(5);
}

The only thing I can thing of (which doesn't really simplify anything) is:

#define PRINT(type) print_ ## type
PRINT(string)("Hello");
PRINT(num)(4);

Or, is there a better way to use that?

Upvotes: 0

Views: 60

Answers (1)

KamilCuk
KamilCuk

Reputation: 140970

You can make the identification to be the first function argument:

#define PRINT(type, value)   print_ ## type(value)
PRINT(string, "Hello");
PRINT(num, 4);

But I see no value in that over just writing printf, as someone will have to learn to write num in case of int, he might as well learn to use %d anyway:

printf("%s\n", "Hello");
printf("%d\n", 4);

Type dispatch is not possible in pre-processor - it's not aware of types. In C11 there's _Generic that allows compiler to choose different function depending on type:

#define PRINT(value) _Generic((value), \
        char *: print_string, \
        int: print_int)(value)
PRINT("Hello");
PRINT(4);

By overloading the macro on each argument and applying such _Generic macro on each argument it's possible to build a replacement for C++ std::cout. So a little self-promotion: that's a topic I explored in yio library that allows just to do:

yprint("Hello ", 4, "\n");

Upvotes: 1

Related Questions