cppmagic: Conditionals
authorDavid Gibson <david@gibson.dropbear.id.au>
Tue, 26 Jan 2016 10:00:01 +0000 (21:00 +1100)
committerDavid Gibson <david@gibson.dropbear.id.au>
Wed, 3 Feb 2016 22:44:13 +0000 (09:44 +1100)
Implement CPPMAGIC_IFELSE which operates similar to the C ? : operator, but
is evaluated at preprocessing time.

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
ccan/cppmagic/cppmagic.h
ccan/cppmagic/test/run.c

index c4454e776392f4edff78ff8289d432ce4e09ddf4..b5c35782f78ca5e58ab16fa45bddb0649c87333c 100644 (file)
 #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 */
index fb2bfb9f95450d0354385843be722c462c25a9a2..0f8917d6a4afa5d8e620504a197fd7ae14cec7b8 100644 (file)
@@ -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();
 }