How to write a macro with optional and variable arguments

I have a macro with a name PRINT(...)that I use in my code that receives a variable number of arguments and acts like printf(gets format and arguments). It is defined as follows:

#define PRINT(...) PRINT(__VA_ARGS__)                     

Now I want to change it so that it has an optional argument, say its name number, and it will add a numerical prefix to the print. For instance:

PRINT("%s", "hi")→ print hi
PRINT(1, "%s", "hi")→ print1: hi

How can I change the macro PRINTto support this?
It is important to say that I do not want to modify any existing call to this macro from my code (in the example, if I have a call PRINT("%s", "hi")), it should remain unchanged after the change).
In addition, I cannot create a new macro for this purpose - I must use an existing macro for this purpose PRINT(but, outside the course, I can change its definition argument).
Any idea how I can do this?

Edit: I saw this post about a macro variable, but it differs from what I ask here, because the argument numbermust be a recognized variable, which will be considered in the implementation PRINTas -1if the call PRINTdoes not contain an argument number(it -1will be an indicator for printing the number), and in Otherwise, it will print the number prefix.

+4
source share
2 answers

C11 _Generic. . , _Generic , . , , .

#define PRINT(fst, ...) \
( \
    _Generic((0, fst), char *: 1, default: 0) ? \
    PRINTNL(fst, __VA_ARGS__) : \
    PRINTL(fst, __VA_ARGS__) \
)

PRINTNL PRINTL .

:

#define PRINTNL(...) printf(__VA_ARGS__)
#define PRINTL (n, ...) ({ \
    printf("%d: ", n); \
    printf(__VA_ARGS__); \
})
+2

, , , . , PRINT(...) printf(__VA_ARGS__):

#define PRINT(...) printf(__VA_ARGS__)

, NPRINT, printf, , :

#define NPRINT(number, fmt, ...) (printf("%d: ", number), printf(fmt, __VA_ARGS__))

#include <stdio.h>

int main(void) {
    NPRINT(1, "%s\n", "hi");
}

, , printf - , , :

#define NPRINT(number, fmt, ...) (printf("%d " fmt, number, __VA_ARGS__))

, PRINT, , , - , .

, number, -1:, :

#define PRINT(...) NPRINT(-1, __VA_ARGS__)
+1

Source: https://habr.com/ru/post/1683091/


All Articles