Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the definition of container_of macro

instead of defining container_of as:

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

Why won't this simply work :

#define container_of(ptr, type, member) ({ \
                    (type *)( (char *)(ptr) - offsetof(type,member) );})

what's the usage of first line in the definition?

like image 329
nzomkxia Avatar asked Nov 19 '12 08:11

nzomkxia


1 Answers

It adds some level of type safety. With your second version, I could pass anything in for ptr and it would compile fine. With the kernel's version, you'll at least get a warning if you pass in a pointer for ptr that doesn't match the type of type.member.

like image 141
Roland Avatar answered Oct 01 '22 14:10

Roland