nzomkxia
nzomkxia

Reputation: 1267

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?

Upvotes: 6

Views: 550

Answers (1)

Roland
Roland

Reputation: 6563

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.

Upvotes: 9

Related Questions