/*
* C99 has support of variable arguments in macros statement
* (called variadic macro) just like variable argument function, Macros also
* can be of variable number of augments
* This program illustrate variadic macros
*/
#include <stdio.h>
/*
* Simple Macro definition
* which allows to print whatever the way you want
* in Macro definition "..." indicates variadic macro, OP() definition is
* mixture of named args and variable number of aguments, it is possible
* to have macro of complete variable number of args
* like DISPLAY in below example
*/
#define OP(format, exp, ...) printf(format, exp, ##__VA_ARGS__)
#define DISPLAY(...) printf(__VA_ARGS__)
int main()
{
int a=3, b=4, c=5;
OP("%s %d\n", "Result after add", a+b);
OP("%s %d %s %d\n", "Result after add", a+b+c, "Result after sub", a-b);
OP("%s\n", "This is test program");
OP("%s %f\n", "Division of a/b", a/(double)b);
OP("%s %s %s %s\n", "This", "is", "Variadic", "Macro");
int main()
{
int a=3, b=4, c=5;
OP("%s %d\n", "Result after add", a+b);
OP("%s %d %s %d\n", "Result after add", a+b+c, "Result after sub", a-b);
OP("%s\n", "This is test program");
OP("%s %f\n", "Division of a/b", a/(double)b);
OP("%s %s %s %s\n", "This", "is", "Variadic", "Macro");
/* This show why we used ## token paste operator at macro definition,
* our definition indicates 2 mandatory args and variable number of args,
* if we left out variable argument in macro statement(in case if we have only
* mandatory args) program will not compile, as in below statement, such
* cases ## will come to resuce, ## operator has a special meaning
* when placed between a comma and a variable argument, in case if we
* don't have variable argument, ## will delete the comma (,) between
* last mandatory argument and __VA_ARGS__
*/
OP("%s\n", "Only two args");
OP("%s\n", "Only two args");
DISPLAY("%s %s\n", "Variadic", "Macro only");
return 0;
}
}
Comments
Post a Comment