0

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?

6
  • Try _Generic from C11? Commented Mar 1, 2021 at 23:11
  • @tstanisl thanks, could you show an example please? I've never used that type(?) before. Commented Mar 1, 2021 at 23:12
  • stackoverflow.com/q/9804371/4989451 Commented Mar 1, 2021 at 23:20
  • 1
    You can't do this with the preprocessor. The preprocessor deals with compile-time values, not run-time values. Commented Mar 1, 2021 at 23:24
  • You can do this with the preprocessor, just not with precisely the syntax you show. Would you accept a syntax requiring PRINT(string, "Hello"); instead of PRINT(string)("Hello"); ? Commented Mar 1, 2021 at 23:29

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.