3

Possible Duplicate:
C/C++: How to make a variadic macro (variable number of arguments)

Just wondering if this is at all possible., so instead of how im currently handling logging and messages with multiple parameters im having to have a number of different macros for each case such as:

#define MSG(             msg                                    )
#define MSG1(            fmt, arg1                              )
#define MSG2(            fmt, arg1, arg2                        )
#define MSG3(            fmt, arg1, arg2, arg3                  )
#define MSG4(            fmt, arg1, arg2, arg3, arg4            )
#define MSG5(            fmt, arg1, arg2, arg3, arg4, arg5      )
#define MSG6(            fmt, arg1, arg2, arg3, arg4, arg5, arg6)

is there any way of defining just one macro that can accept any number of arguments?

thanks

Community
  • 1
  • 1
Stowelly
  • 1,260
  • 2
  • 12
  • 31

2 Answers2

2

Well since @GMan didn't want to put that as an answer himself, have a look at variadic macros which are part of the C99 standard.

Your question is tagged C++ though. Variadic macros are not part of the C++ standard but they are supported by most compilers anyway: GCC and MSVC++ starting from MSVC2005.

Gregory Pakosz
  • 69,011
  • 20
  • 139
  • 164
  • 2
    since you're trying to define `MSG1(fmt, arg1) I bet you're wanting to use something like `printf`? – Gregory Pakosz Jan 08 '10 at 09:54
  • a number of things to be honest, all will be formatted strings, but will be outputting to bits of UI, log files and possibly message boxes. but yeah you are right this is C not C++, will give variadic macros a try thanks – Stowelly Jan 08 '10 at 09:58
  • 2
    while you're playing with variadic macros, here is a shameless plug to an answer I gave to another question http://stackoverflow.com/questions/1872220/is-it-possible-to-iterate-over-arguments-in-variadic-macros/1872506#1872506 – Gregory Pakosz Jan 08 '10 at 10:01
  • Bah, after all this it seems va args are banned as part of our coding standard. i guess there isnt really any other way :( – Stowelly Jan 08 '10 at 10:57
  • 1
    limits are there to be pushed :D – Gregory Pakosz Jan 08 '10 at 11:09
  • I was informed about a clause in my contract that states "anyone who uses va args will be shot" – Stowelly Jan 08 '10 at 11:14
2

The following is the macro I use to generate exceptions - there is no need for variadic macros, which C++ does not currently support:

#define CSVTHROW( msg )         \
{                                 \
    std::ostringstream os;         \
    os << msg;                     \
    throw CSVED::Exception(os.str());   \
}                               \

In use it allows you to say things like:

CSVTHROW( "Problem caused by " << x << " being less than " << y );

You can easily replace the throw statement with a write to your log.