objective-c macro variadic … for my LOG

I had almost forgotten about macro variadic … until I needed it. When a macro (or function) is declared with a variable number of arguments then this macro is called variadic. The syntax in order to define  macro is similar to that of a function (__VA_ARGS__) :
#define eprintf() fprintf (stderr, __VA_ARGS__)
Where the 3 dots () are replaced with __VA_ARGS__ at runtime.

EXAMPLE of macro :

#define NAMEOFMACRO1(...) fnc (__VA_ARGS__)
//if there is a single mandatory variable (x) and after a variable number of arguments then
#define NAMEOFMACRO2(x,...) fnc (x,__VA_ARGS__)

When you invoke the macro : NAMEOFMACRO2(a,b,c,d) the token b,c,d replaces the “placeholder” __VA_ARGS__

#define NAMEOFMACRO2(x,...) fnc (x,__VA_ARGS__)
NAMEOFMACRO2("a",b,"c",12) Transfrormed to fnc("a",b,"c",12)
NAMEOFMACRO2("a","c",12)   Transfrormed to fnc("a","c",12)
NAMEOFMACRO2("a")          Transfrormed to fnc("a", )

If you need more details see here :


I used variadic for  “LOG macro” with objective-c … an example of use is below :

#defile LL_ERROR 1
#defile LL_INFO 2
#defile LL_DEBUG 3

#define LOG_ERROR(...) if (logLev>=LL_ERROR) NSLog(@"ERROR %@,%@ - %@ @ (%@:%d)",@""__DATE__"",@""__TIME__"",[NSString stringWithFormat:__VA_ARGS__],@""__FILE__"",__LINE__);
#define LOG_INFO (...) if (logLev>=LL_INFO)  NSLog(@"INFO: %@,%@ - %@ @ (%@:%d)",@""__DATE__"",@""__TIME__"",[NSString stringWithFormat:__VA_ARGS__],@""__FILE__"",__LINE__);
#define LOG_DEBUG(...) if (logLev>=LL_DEBUG) NSLog(@"DEBUG:%@,%@ - %@ @ (%@:%d)",@""__DATE__"",@""__TIME__"",[NSString stringWithFormat:__VA_ARGS__],@""__FILE__"",__LINE__);

Example :

setLogLevel(LL_DEBUG); //set variable logLev
LOG_DEBUG(@"Initialize client settings");
LOG_ERROR(@"Error getting key '%@' from configuration '%@' " ,key,configName);
Powered by WP Review