From: Andre Noll Date: Fri, 4 Feb 2011 06:46:28 +0000 (+0100) Subject: Improve ARRAY_SIZE macro. X-Git-Tag: v0.4.6~18^2 X-Git-Url: http://git.tue.mpg.de/?a=commitdiff_plain;h=b908fa3f5577d1f64bd8628d03a344aee2ca6fa1;p=paraslash.git Improve ARRAY_SIZE macro. Compilation now fails if the given argument not an array but a pointer. Idea taken from ccan. Thanks Rusty! --- diff --git a/gcc-compat.h b/gcc-compat.h index ffd714f7..45d9c9ba 100644 --- a/gcc-compat.h +++ b/gcc-compat.h @@ -23,3 +23,4 @@ # endif #define _static_inline_ static inline + diff --git a/para.h b/para.h index c5e12fe6..c30e4710 100644 --- a/para.h +++ b/para.h @@ -170,8 +170,23 @@ _static_inline_ long int para_random(unsigned max) typeof(y) _divisor = y; \ ((x) + _divisor - 1) / _divisor; }) +/** + * Assert a build-time dependency, as an expression. + * + * \param cond The compile-time condition which must be true. + * + * Compilation will fail if the condition isn't true, or can't be evaluated by + * the compiler. This can be used in an expression: its value is "0". + * + * Taken from ccan. + */ +#define EXPR_BUILD_ASSERT(cond) (sizeof(char [1 - 2 * !(cond)]) - 1) + +/* &a[0] degrades to a pointer: a different type from an array */ +#define _array_size_chk(arr) EXPR_BUILD_ASSERT(\ + !__builtin_types_compatible_p(typeof(arr), typeof(&(arr)[0]))) /** Get the size of an array */ -#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + _array_size_chk(arr)) /** * Wrapper for isspace.