From: David Gibson Date: Tue, 26 Jan 2016 10:00:01 +0000 (+1100) Subject: cppmagic: Conditionals X-Git-Url: http://git.ozlabs.org/?p=ccan;a=commitdiff_plain;h=395a2f841356e5bba4935a24093d30d67c1f3ef5 cppmagic: Conditionals Implement CPPMAGIC_IFELSE which operates similar to the C ? : operator, but is evaluated at preprocessing time. Signed-off-by: David Gibson --- diff --git a/ccan/cppmagic/cppmagic.h b/ccan/cppmagic/cppmagic.h index c4454e77..b5c35782 100644 --- a/ccan/cppmagic/cppmagic.h +++ b/ccan/cppmagic/cppmagic.h @@ -84,4 +84,18 @@ #define CPPMAGIC_ISEMPTY(...) \ CPPMAGIC_ISZERO(CPPMAGIC_NONEMPTY(__VA_ARGS__)) +/* + * CPPMAGIC_IFELSE - preprocessor conditional + * + * CPPMAGIC_IFELSE(@cond)(@if)(@else) + * expands to @else if @cond is '0', otherwise expands to @if + */ +#define _CPPMAGIC_IF_0(...) _CPPMAGIC_IF_0_ELSE +#define _CPPMAGIC_IF_1(...) __VA_ARGS__ _CPPMAGIC_IF_1_ELSE +#define _CPPMAGIC_IF_0_ELSE(...) __VA_ARGS__ +#define _CPPMAGIC_IF_1_ELSE(...) +#define _CPPMAGIC_IFELSE(cond_) CPPMAGIC_GLUE2(_CPPMAGIC_IF_, cond_) +#define CPPMAGIC_IFELSE(cond_) \ + _CPPMAGIC_IFELSE(CPPMAGIC_NONZERO(cond_)) + #endif /* CCAN_CPPMAGIC_H */ diff --git a/ccan/cppmagic/test/run.c b/ccan/cppmagic/test/run.c index fb2bfb9f..0f8917d6 100644 --- a/ccan/cppmagic/test/run.c +++ b/ccan/cppmagic/test/run.c @@ -17,7 +17,7 @@ static inline void check1(const char *orig, const char *expand, int main(void) { - plan_tests(21); + plan_tests(24); CHECK1(CPPMAGIC_NOTHING(), ""); CHECK1(CPPMAGIC_GLUE2(a, b), "ab"); @@ -47,6 +47,10 @@ int main(void) CHECK1(CPPMAGIC_ISEMPTY(0), "0"); CHECK1(CPPMAGIC_ISEMPTY(a, b, c), "0"); + CHECK1(CPPMAGIC_IFELSE(0)(abc)(def), "def"); + CHECK1(CPPMAGIC_IFELSE(1)(abc)(def), "abc"); + CHECK1(CPPMAGIC_IFELSE(not zero)(abc)(def), "abc"); + /* This exits depending on whether all tests passed */ return exit_status(); }