0

Possible Duplicate:
Rationale behind the container_of macro in linux/list.h

#define container_of(ptr, type, member) ({                      \
        const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
        (type *)( (char *)__mptr - offsetof(type,member) );})\

Why do we need to construct mptr here instead of casting ptr directly to a char* ?

Community
  • 1
  • 1
mk_
  • 407
  • 1
  • 3
  • 11

2 Answers2

1

Type safety, it assures that mptr is of the same type as pointer to member instead of just casting. If it's not you will get a warning.

iabdalkader
  • 16,363
  • 4
  • 44
  • 70
0

The macro as given in the kernel has a type check, namely it ensures that ptr has a type that is assignment compatible to the type "pointer to the type of member".

E.g if by accident ptr happens to be an integer, a cast would be perfectly happy to interpret this as a char*.

Jens Gustedt
  • 74,635
  • 5
  • 99
  • 170