Add macro to safely derive the size of an array

This commit is contained in:
Lucas De Marchi 2011-11-29 17:59:58 -02:00
parent 191ab4b9e0
commit aa1c3521de

View File

@ -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))