From: Christophe CURIS <[email protected]>

The new macro 'wlengthof' returns the number of elements for which a local
array have been defined, which makes code easier to read than the
previous [sizeof() / sizeof([0]) ] construct.

The macro includes a static assertion to stop compilation if it is being
used on a pointer, for which we cannot know the size of the array, to
avoid generating dummy result. This can work only with C11 which
standardised the static assertions.

Signed-off-by: Christophe CURIS <[email protected]>
---
 WINGs/WINGs/WUtil.h | 31 +++++++++++++++++++++++++++++++
 configure.ac        |  2 +-
 2 files changed, 32 insertions(+), 1 deletion(-)

diff --git a/WINGs/WINGs/WUtil.h b/WINGs/WINGs/WUtil.h
index f14af47..386f77b 100644
--- a/WINGs/WINGs/WUtil.h
+++ b/WINGs/WINGs/WUtil.h
@@ -88,6 +88,27 @@
 #endif /* !NDEBUG */
 
 
+#ifdef static_assert
+# define _wutil_static_assert(check, message) static_assert(check, message)
+#else
+# ifdef __STDC_VERSION__
+#  if __STDC_VERSION__ >= 201112L
+/*
+ * Ideally, we would like to include <assert.h> to have 'static_assert'
+ * properly defined, but as we have to be sure about portability and
+ * because we're a public header we can't count on 'configure' to tell
+ * us about availability, so we use the raw C11 keyword
+ */
+#   define _wutil_static_assert(check, message) _Static_assert(check, message)
+#  else
+#   define _wutil_static_assert(check, message) /**/
+#  endif
+# else
+#  define _wutil_static_assert(check, message) /**/
+# endif
+#endif
+
+
 #ifdef __cplusplus
 extern "C" {
 #endif /* __cplusplus */
@@ -182,6 +203,16 @@ typedef void WMNotificationObserverAction(void 
*observerData,
                                           WMNotification *notification);
 
 
+/* ---[ Macros ]---------------------------------------------------------- */
+
+#define wlengthof(array)  \
+       ({   \
+               _wutil_static_assert(sizeof(array) > sizeof(array[0]),   \
+                                    "the macro 'wlengthof' cannot be used on 
pointers, only on known size arrays");   \
+               sizeof(array) / sizeof(array[0]);   \
+       })
+
+
 /* ---[ WINGs/memory.c ]-------------------------------------------------- */
 
 void* wmalloc(size_t size);
diff --git a/configure.ac b/configure.ac
index 310e679..b46b575 100644
--- a/configure.ac
+++ b/configure.ac
@@ -54,7 +54,7 @@ WINGS_VERSION=$WINGS_CURRENT:$WINGS_REVISION:$WINGS_AGE
 AC_SUBST(WINGS_VERSION)
 dnl
 dnl libWUtil
-WUTIL_CURRENT=3
+WUTIL_CURRENT=4
 WUTIL_REVISION=0
 WUTIL_AGE=0
 WUTIL_VERSION=$WUTIL_CURRENT:$WUTIL_REVISION:$WUTIL_AGE
-- 
1.8.4.rc3


-- 
To unsubscribe, send mail to [email protected].

Reply via email to