[ccan] [PATCH 3/5] cppmagic: Conditionals

David Gibson david at gibson.dropbear.id.au
Wed Jan 27 22:39:59 AEDT 2016


Implement CPPMAGIC_IFELSE which operates similar to the C ? : operator, but
is evaluated at preprocessing time.

Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
---
 ccan/cppmagic/cppmagic.h | 14 ++++++++++++++
 ccan/cppmagic/test/run.c |  6 +++++-
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/ccan/cppmagic/cppmagic.h b/ccan/cppmagic/cppmagic.h
index c4454e7..b5c3578 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 fb2bfb9..0f8917d 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();
 }
-- 
2.5.0



More information about the ccan mailing list