Macro with optional arg and variable args for printf?

时间:2015-05-04 19:52:32

标签: c macros printf c99

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?

0 个答案:

没有答案