Like functions, we can also pass variable length arguments to macros. For this we will use the following preprocessor identifiers.
To support variable length arguments in macro, we must include ellipses (…) in macro definition. There is also “__VA_ARGS__” preprocessing identifier which takes care of variable length argument substitutions which are provided to macro. Concatenation operator ## (aka paste operator) is used to concatenate variable arguments.
Let us see with example. Below macro takes variable length argument like “printf()” function. This macro is for error logging. The macro prints filename followed by line number, and finally it prints info/error message. First arguments “prio” determines the priority of message, i.e. whether it is information message or error, “stream” may be “standard output” or “standard error”. It displays INFO messages on stdout and ERROR messages on stderr stream.
Compile and run the above program, it produces below result.
[narendra@/media/partition/GFG]$ ./variable_length [ERR] : variable_length.c : 26 : Failed to open file [INFO] : variable_length.c : 27 : Hello Geeks for Geeks [INFO] : variable_length.c : 28 : 10 + 20 = 30 [narendra@/media/partition/GFG]$
This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to Count Variable Numbers of Arguments in C?
- Multiline macros in C
- Branch prediction macros in GCC
- Macros vs Functions
- Data Type Ranges and their macros in C++
- Hygienic Macros : An Introduction
- X-Macros in C
- Predefined Macros in C with Examples
- Macros and its types in C/C++
- Interesting Facts about Macros and Preprocessors in C
- Can we access global variable if there is a local variable with same name?
- Internal static variable vs. External static variable with Examples in C
- When do we pass arguments by reference or pointer?
- Templates and Default Arguments
- Default arguments and virtual function
- Some Interesting facts about default arguments in C++
- Command line arguments in C/C++
- C++ | Function Overloading and Default Arguments | Question 5
- C++ | Function Overloading and Default Arguments | Question 2
- C++ | Function Overloading and Default Arguments | Question 3