From fce288f6572c135f98cbabd893d0d93d1ff5a244 Mon Sep 17 00:00:00 2001 From: Przemyslaw Pawelczyk Date: Sat, 5 Jul 2014 00:31:04 +0200 Subject: [PATCH] Rewrite container_of macro without using statement expression. Statement expression is GNU C extension, not present in ISO standard. Type checking works now via implicit conversion performed for compound literal (compound literals are available since C99). typeof is only used on GNUC compilers like gcc or clang. --- utils.h | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/utils.h b/utils.h index c2277e9..991af9c 100644 --- a/utils.h +++ b/utils.h @@ -20,6 +20,12 @@ struct sockaddr_in; #endif +#ifdef __GNUC__ +#define member_type(type, member) __typeof(((type *)0)->member) +#else +#define member_type(type, member) const void +#endif + /** * container_of - cast a member of a structure out to the containing structure * @ptr: the pointer to the member. @@ -27,9 +33,11 @@ struct sockaddr_in; * @member: the name of the member within the struct. * */ -#define container_of(ptr, type, member) ({ \ - const typeof( ((type *)0)->member ) *__mptr = (ptr); \ - (type *)( (char *)__mptr - offsetof(type,member) );}) +#define container_of(ptr, type, member) \ + ((type *)( \ + (char *)(member_type(type, member) *){ ptr } - offsetof(type, member) \ + )) + #define clamp_value(value, min_val, max_val) do { \ if (value < min_val) \