Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Variable length arguments for Macros in C
In C, we can use variable length arguments for macros, similar to how we use them with functions. This is achieved using ellipsis (…) and the special __VA_ARGS__ identifier. The concatenation operator ## is used to handle cases where no variable arguments are provided.
Syntax
#define MACRO_NAME(fixed_params, ...) macro_body __VA_ARGS__
Where __VA_ARGS__ represents all the variable arguments passed to the macro, and ## can be used for token pasting.
Example: Logging Macro with Variable Arguments
This example demonstrates a logging macro that accepts variable arguments like printf(). The macro prints the filename, line number, and custom error messages −
#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" <br>", \
str, __FILE__, __LINE__, ##__VA_ARGS__);\
} while (0)
int main() {
char *s = "Test String";
/* Simple message without additional arguments */
LOG_MESSAGE(ERR, STD_ERR, "Unable to open the file");
/* Message with string argument */
LOG_MESSAGE(INFO, STD_OUT, "%s is passed as argument", s);
/* Message with multiple integer arguments */
LOG_MESSAGE(INFO, STD_OUT, "%d + %d = %d", 14, 16, (14 + 16));
return 0;
}
[ERROR] : /tmp/code.c : 18 : Unable to open the file [INFORMATION] : /tmp/code.c : 21 : Test String is passed as argument [INFORMATION] : /tmp/code.c : 24 : 14 + 16 = 30
Key Points
-
__VA_ARGS__expands to all the variable arguments passed to the macro. - The
##operator before__VA_ARGS__removes the preceding comma if no arguments are provided. - The
do-while(0)construct ensures the macro behaves like a single statement. - Variable argument macros are available in C99 and later standards.
Conclusion
Variable length argument macros in C provide a powerful way to create flexible, printf-like macros. Using __VA_ARGS__ and the ## operator, we can create robust logging and debugging utilities that accept any number of arguments.
