0

I'm trying to setup a specialized macro for printf. For example:

// Not sure how to implement ...
#define MYPRINT(?) ???

This simple case uses a string literal formatter and a variable number of corresponding args

MYPRINT("Hello World %d %d %d", 1, 2, 3);

This case is similar expect it has one arg that precedes the string literal

MYPRINT(OPTIONAL_ARG, "Hello World %d %d %d", 1, 2, 3);

As you can see, I would like the macro to be called using the same MYPRINT statement.

I've reviewed solutions that overload macros by counting the number of args - but I don't think that will work I my case?

The only solution that looks possible so far is to setup the macros such that a "selector" parameter always shows up and that allows you to select which implementation you want to use. In my case I could put the selector index at the beginning. A "0" index could give me the first macro and a "1" could give me the second:

MYPRINT(0, "Hello World %d %d %d", 1, 2, 3);
MYPRINT(1, OPTIONAL_ARG, "Hello World %d %d %d", 1, 2, 3);

Does anyone know if such a thing can be achieved without a selector parameter?

Perhaps if there was a "compile time" way to distinguish between an int and a string literal then the macro is defined based on that?

Community
  • 1
  • 1
dtmland
  • 2,136
  • 4
  • 22
  • 45
  • 2
    What type is `OPTIONAL_ARG`? If it can't be a string, you might be able to do something with generic expressions. If it can be a string, there's no way to distinguish between `MYPRINT(optional_string, format_string)` and `MYPRINT(format_string, thing_to_insert)`. – user2357112 May 04 '15 at 19:56
  • In my case it will not be a string – dtmland May 04 '15 at 19:57
  • @user2357112 How might generic expressions help? – dtmland May 05 '15 at 01:12
  • 1
    Something like `_Generic(first_arg, char *:printf(stuff), int: printf(other_stuff))`. [Here's an explanation of generic selection expressions.](http://www.robertgamble.net/2012/01/c11-generic-selections.html) – user2357112 May 05 '15 at 01:19
  • @user2357112 Ah yes! That should work in `C11`? How about `C99`? – dtmland May 06 '15 at 20:14
  • Dunno. Someone better at macros might be able to devise a test that works, but I'm not a macro expert. – user2357112 May 06 '15 at 20:21

0 Answers0