This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Macros With A Variable Number Of Arguments...
  Submitted by



A friend just asked me if it would be possible to use the ellipsis (...) in a macro's parameter list, just like it is used in the printf() function:

int printf(const char* fmt, ...); 



The answer is NO. You can't do that with a macro. There's a nice workaround that I've used now and then, though. It uses the fact that, when parsing the parameters passed into a macro, the C preprocessor parses nested sets of parenthesis, and will not use the commas found inside of those nested parenthesis to separate the parameters. So, for example, my solution for a simple printf() wrapper would be something like this:

bool g_DoLog = false;
#define LogPrintf(a) if (!g_DoLog) {} else printf a 



Now, you can use the macro like this:

g_DoLog = true;
..
LogPrintf(("Hello %s\n", "World")); 



Note that the macro above has complete function semantics: each parameter is only evaluated once, it requires the semicolon and it is a single statement. The double parenthesis are necessary in the general case., but they can be obviated in this example by doing it like this:

#define LogPrintf if (!g_DoLog) {} else printf
..
LogPrintf("Hello %s\n", "World"); 



This requires the multiple parameters to go at the end, however, which may not be always possible.

You can also have other non-variable parameters in the macro:

int g_LogLevel = 0;
#define LogPrintf(l,a) if (g_LogLevel < (unsigned int)(l)) {} else printf a
..
LogPrintf(3, ("Hello %s\n", "World")); 

The double parenthesis are necessary in this case. Still, this can also be done as follows:

unsigned int g_LogLevel = 0;
#define LogPrintf(l) if (g_LogLevel <= (unsigned int)(l)) {} else printf
..
LogPrintf(3)("Hello %s\n", "World"); 

The possibilities are actually quite endless.

Salutaciones,
JCAB


The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.