Re: Fwd: Question about container_of macro.

Laurent Pinchart <[email protected]> Fri, 18 Jan 2008 10:14:44 +0100
Newsgroups gmane.linux.usb.devel
Message-ID <[email protected]>
On Friday 18 January 2008 05:29, Manish Katiyar wrote:
> On Jan 18, 2008 9:45 AM, Manish Katiyar <[email protected]> wrote:
> > Hi Laurent,
> >
> > On Jan 18, 2008 5:31 AM, Laurent Pinchart <[email protected]> 
wrote:
> > > On Thursday 17 January 2008, Alan Stern wrote:
> > > > On Thu, 17 Jan 2008, Manish Katiyar wrote:
> > > > > My question is 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) );})
> > > >
> > > > Indeed, or even this:
> > > >
> > > > #define container_of(ptr, type, member) \
> > > >                       ((type *) ((char *)(ptr) -
> > > > offsetof(type,member)))
> > >
> > > If I'm not mistaken, that's because
> > >
> > > const typeof( ((type *)0)->member ) *__mptr = (ptr);
> > >
> > > will warn (or maybe even bail out ?) if ptr is not a pointer to a
> > > variable of member's type.
> >
> > But even if ptr is not a variable of member's type, in the second line
> > we are force typecasting it to char * and then subtracting. I guess it
> > will not warn. I tried in a simple program and it doesn't shout.
> > Below is the program

That's why you need

const typeof( ((type *)0)->member ) *__mptr = (ptr);

in addition to

(type *)( (char *)__mptr - offsetof(type,member) );

otherwise you'll get no warning.

Laurent Pinchart

-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
[email protected]
To unsubscribe, use the last form field at:
https://lists.sourceforge.net/lists/listinfo/linux-usb-devel