Skip to content

Instantly share code, notes, and snippets.

@santileortiz
Created March 29, 2020 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santileortiz/9a5c60a545d01a70dc1d9a631b9fca40 to your computer and use it in GitHub Desktop.
Save santileortiz/9a5c60a545d01a70dc1d9a631b9fca40 to your computer and use it in GitHub Desktop.
Conditional macro based on number of passed arguments
// This is a way of executing a different macro based on the number of argument
// passed to a macro with variable arguments. Essentially this is a way of
// executing macros conditionally even though C doesn't support using #if inside
// a macro definition.
//
// Source: https://stackoverflow.com/questions/3046889/optional-parameters-with-c-macros
// The multiple macros that you would need anyway [as per: Crazy Eddie]
#define XXX_0() <code for no arguments>
#define XXX_1(A) <code for one argument>
#define XXX_2(A,B) <code for two arguments>
#define XXX_3(A,B,C) <code for three arguments>
#define XXX_4(A,B,C,D) <code for four arguments>
// The interim macro that simply strips the excess and ends up with the required macro
#define XXX_X(x,A,B,C,D,FUNC, ...) FUNC
// The macro that the programmer uses
#define XXX(...) XXX_X(,##__VA_ARGS__,\
XXX_4(__VA_ARGS__),\
XXX_3(__VA_ARGS__),\
XXX_2(__VA_ARGS__),\
XXX_1(__VA_ARGS__),\
XXX_0(__VA_ARGS__)\
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment