Skip to contentSkip to conversation

container-of Implementation

DISCUSSION Schrober 3 participants 3 messages Jan 14, 2013

lore
Share & tools
lore

Schrober

author
#0 lore raw

Hi,

I wondered why the container_of implementation is so complicated.

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

isn't the __mptr not unnecessary? Why not following version?

#define container_of(ptr, type, member) \
    ((type *)((char *)(ptr) - offsetof(type, member)))
Signature · 1 line
Franz Schrober
#1 lore raw
Quoted 4 lines · Schrober

Hi,

I wondered why the container_of implementation is so complicated.

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

isn't the __mptr not unnecessary? Why not following version?

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

Compile-time type checking. The first version requires ptr to be assignment-compatible with the type of the struct member, the second version accepts random junk for ptr.

#2 lore raw
In reply to Schrober
Quoted 10 lines · Schrober

I wondered why the container_of implementation is so complicated.

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

isn't the __mptr not unnecessary? Why not following version?

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

The __mptr construct will cause a compiler warning if ptr is of the wrong type.

Gr{oetje,eeting}s,

Geert

--
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But when I'm talking to journalists I just say "programmer" or something like that.
-- Linus Torvalds