Variable length arguments for Macros in C

CServer Side ProgrammingProgramming

We know that we can use variable length arguments for functions in C. For that we have to use ellipsis (…). Similarly for macros, we can use variable length arguments. Here also we have to include ellipsis, The ‘__VA_ARGS__’ is used to handle variable length arguments. Concatenation operator ‘##’ is used to concatenate the variable arguments.

In this example, the Macro will take variable length argument like the printf() or scanf() function. In this macro, we will print the filename, line number, and error messages. The first argument is pr. This is used to determine the priority i.e. whether it is normal info string or error

Example

#include <stdio.h>
#define INFO 1
#define ERR 2
#define STD_OUT stdout
#define STD_ERR stderr
#define LOG_MESSAGE(pr, strm, msg, ...) do {\
   char *str;\
   if (pr == INFO)\
      str = "INFORMATION";\
   else if (pr == ERR)\
      str = "ERROR";\
      fprintf(strm, "[%s] : %s : %d : "msg" \n", \
      str, __FILE__, __LINE__, ##__VA_ARGS__);\
} while (0)
int main(void) {
   char *s = "Test String";
   LOG_MESSAGE(ERR, STD_ERR, "Unable to open the file"); //here normal message will be printed
   LOG_MESSAGE(INFO, STD_OUT, "%s is passed as argument", s); //pass string argument
   LOG_MESSAGE(INFO, STD_OUT, "%d + %d = %d", 14, 16, (14 + 16)); //Provide integer
}

Output

[ERROR] : D:\text.c : 21 : Unable to open the file
[INFORMATION] : D:\text.c : 23 : Test String is passed as argument
[INFORMATION] : D:\text.c : 25 : 14 + 16 = 30
raja
Published on 03-May-2019 07:21:02
Advertisements