Last active
September 19, 2020 03:51
-
-
Save Shylock-Hg/3cf18bab9ee57f9530a21df0ff75ab91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stddef.h> | |
#include <stdbool.h> | |
#include <assert.h> | |
/*! \brief transfer the variadic parameters to string literal | |
* */ | |
#define argsstr(...) (#__VA_ARGS__) | |
/*! \brief check the validation of variadic parameters | |
* \param dummy required before variadic parameters | |
* \param ... the variadic parameters | |
* */ | |
int check(int dummy, ...) { | |
return dummy; | |
} | |
size_t count_args_by_str(const char * args) { | |
bool in_str = false; | |
bool in_char = false; | |
size_t count = 0; | |
if (NULL == args || '\0' == *args) { | |
return count; | |
} | |
while('\0' != *args) { | |
if ('\"' == *args && '\\' != *(args-1)) { | |
in_str = !in_str; | |
} | |
if ('\'' == *args && '\\' != *(args-1)) { | |
in_char = !in_char; | |
} | |
if (*args == ',' && !in_str && !in_char) { | |
count++; | |
} | |
args++; | |
} | |
return count + 1; | |
} | |
#define count_args(...) (check(0, ## __VA_ARGS__), \ | |
count_args_by_str(argsstr(__VA_ARGS__))) | |
int main(int argc, char * argv[]) { | |
assert(0 == count_args()); | |
assert(1 == count_args(1)); | |
assert(1 == count_args("")); | |
assert(1 == count_args('\'')); | |
assert(2 == count_args('\'', "Hello, World!")); | |
assert(3 == count_args(-1.1, ',', ",,,")); | |
// invalid call like count_args(3, ), count_args(,) and count_args(, 3) will | |
// invoke compile error | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment