I have macros that will either expand into a number (in my example, cases 2 and 4), or nothing (in my example, cases 1 and 3). Nothingness isn't desirable for me, so I need other macros that will detect and replace the nothingness.
I was able to create a macro, OLD_CHECK
, that would detect the nothingness-case and replace it with a 0. (Case 1)
I want to improve on it and create a new macro, NEW_CHECK
, that will detect the nothingness-case and replace it with a default value. (Case 3)
/* what I currently have */
print("case 1: [%d]", OLD_CHECK( )); // case 1: [0]
print("case 2: [%d]", OLD_CHECK(5)); // case 2: [5]
/* what I hope to achieve */
int default_value = 7;
print("case 3: [%d]", NEW_CHECK(default_value, )); // case 3: [7]
print("case 4: [%d]", NEW_CHECK(default_value, 5)); // case 4: [5]
To write OLD_CHECK
, I was using the number of arguments. This method does not seem to feasible to write NEW_CHECK
with, as cases 3 and 4 are both detected as having 2 arguments.
Edit: this is the macro that works to catch and handle Cases 1 and 2:
/* Given a dummy and >=1 arguments, expand to the first argument */
#define FIRST_ONE(dummy, a1, ...) a1
/* if "..." is nonblank, expand to the first arg of "...". otherwise, expand to 0 */
#define OLD_CHECK(...) OLD_CHECK_CORE(__VA_ARGS__)
#define OLD_CHECK_CORE(...) FIRST_ONE(dummy, ##__VA_ARGS__, 0)
Edit 2: It is necessary to have the trailing comma in Case 3. It is an unfortunate byproduct of a series of other more-complicated macros.
ANSWERED: This method, given by p00ya, works for me:
#define NEW_CHECK_HELPER(...) , ## __VA_ARGS__
#define NEW_CHECK(default, ...) (default NEW_CHECK_HELPER(__VA_ARGS__))