From: Lucas De Marchi Date: Tue, 29 Nov 2011 19:59:58 +0000 (-0200) Subject: Add macro to safely derive the size of an array X-Git-Tag: v1~180 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=aa1c3521de149f5c8b8f348895844dca6186604f;p=thirdparty%2Fkmod.git Add macro to safely derive the size of an array --- diff --git a/libkmod/macro.h b/libkmod/macro.h index 11e38a7e..d09d6645 100644 --- a/libkmod/macro.h +++ b/libkmod/macro.h @@ -48,6 +48,29 @@ ((char *)(member_ptr) - offsetof(containing_type, member)) \ - check_types_match(*(member_ptr), ((containing_type *)0)->member)) +/** + * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression. + * @cond: the compile-time condition which must be true. + * + * Your compile 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". + * + * Example: + * #define foo_to_char(foo) \ + * ((char *)(foo) \ + * + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0)) + */ +#define BUILD_ASSERT_OR_ZERO(cond) \ + (sizeof(char [1 - 2*!(cond)]) - 1) + +/* Two gcc extensions. + * &a[0] degrades to a pointer: a different type from an array */ +#define _array_size_chk(arr) \ + BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(typeof(arr), \ + typeof(&(arr)[0]))) + +#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + _array_size_chk(arr)) + /* Attributes */ #define __must_check __attribute__((warn_unused_result))