countof(): perform a compile time type checking for static arrays
authorarighi <arighi@38d2e660-2303-0410-9eaa-f027e97ec537>
Mon, 30 Aug 2010 15:48:18 +0000 (15:48 +0000)
committerarighi <arighi@38d2e660-2303-0410-9eaa-f027e97ec537>
Mon, 30 Aug 2010 15:48:18 +0000 (15:48 +0000)
The macro countof() can only work with static arrays, so throw a compile
time error if a pointer is passed as argument.

NOTE: this only works with gcc (not g++).

git-svn-id: https://src.develer.com/svnoss/bertos/trunk@4202 38d2e660-2303-0410-9eaa-f027e97ec537

bertos/cfg/compiler.h

index 907b23e6d1749cf496a675937e580898d1ee0f73..e8a76ab1af9e3fddb5af5bf8a753ab00fb670315 100644 (file)
@@ -531,7 +531,22 @@ typedef unsigned char sigmask_t; /**< Type for signal masks. */
         *
         * \note This macro is non-standard, but implements a very common idiom
         */
-       #define countof(a)  (sizeof(a) / sizeof(*(a)))
+       #if defined(__GNUC__) && !defined(__cplusplus)
+               /*
+                * Perform a compile time type checking: countof() can only
+                * work with static arrays, so throw a compile time error if a
+                * pointer is passed as argument.
+                *
+                * NOTE: the construct __builtin_types_compatible_p() is only
+                * available for C.
+                */
+               #define countof(a) (sizeof(a) / sizeof(*(a)) + \
+                       sizeof(typeof(int[1 - 2 * \
+                               !!__builtin_types_compatible_p(typeof(a), \
+                                               typeof(&a[0]))])) * 0)
+       #else
+               #define countof(a)  (sizeof(a) / sizeof(*(a)))
+       #endif
 #endif
 #ifndef alignof
        /**