🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4411

Re: "Size not needed?"

#4411
From: Richard Krehbiel
Date: Fri, 01 Dec 1995 12:40
58 lines
2348 bytes
erik@kroete2.freinet.de (Erik Corry) wrote:

>Richard Krehbiel (rich@kastle.com) wrote:
>: I wrote:
>: 
>: >Well, actually I'd probably use a macro that I've declared for my own
>: >use...
>: 
>: >#define CONTAINER_P(p,s,m) (s*)((char *)(p)-offsetof(s,m))
>: 
>: >...which, for pointer p which is assumed to be a pointer to member m
>: >of aggregate s, gives a pointer to s.  There's a slight bit more type
>: >checking than the simple cast (I'd love it if I could also be assured
>:                                 --------------------------------------
>: >that p is really the same type as &s.m).  If the member is first,
>:  --------------------------------------
>: >typically the subtraction is optimized away since the offset is a
>: >constant zero.
>: 
>: I've tested the following and it does just what I want:
>: 
>: #define CONTAINER_PTR(p,s,m)  \
>:   ((sizeof(&((s *)0)->m == (p))), \
>:    (s *) ((char *)(p) - offsetof(s,m)))

>Er... That's really quite clever. Keep the old version around
>in case you hit a compiler that doesn't agree.

All I have to do is remove the second line and I have my original
macro back.

>The '==' makes sure the pointer types agree, but why the
>sizeof?

sizeof prevents the first invocation of (p) from really being
evaluated, so I can use an expression for (p) with side effects
without fear.

Run this and see.

#include <stdio.h>

int report(void)
{
    puts("report called.");
    return 1;
}

int main(void)
{
    printf("sizeof int = %d bytes\n",  sizeof(report()));

    return 0;
}

--
Richard Krehbiel, Kastle Systems, Arlington VA USA
rich@kastle.com (work) or richk@cais.com (personal)
Technical Details
Message-ID: <1995Dec1.123705.28246@friend.kastle.com>
Path: arc1-ca.pugleaf.net!uu4news.netcom.com!friend!news
References: <48gu0r$91o@news0.rain.rg.net> <1995Nov17.120551.23493@friend.kastle.com> <48iljp$jl5@news0.rain.rg.net> <DI9nH2.DIy@kroete2.freinet.de> <1995Nov20.125350.9627@friend.kastle.com> <1995Nov28.185702.4482@friend.kastle.com> <DItx1n.IrC@kroete2.freinet.de>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c
Path: arc1-ca.pugleaf.net!uu4news.netcom.com!friend!news
From: rich@kastle.com (Richard Krehbiel)
Subject: Re: "Size not needed?"
Message-ID: <1995Dec1.123705.28246@friend.kastle.com>
Sender: news@friend.kastle.com (News)
Reply-To: rich@kastle.com
Organization: Kastle Development Associates
X-Newsreader: Forte Free Agent 1.0.82
References: <48gu0r$91o@news0.rain.rg.net> <1995Nov17.120551.23493@friend.kastle.com> <48iljp$jl5@news0.rain.rg.net> <DI9nH2.DIy@kroete2.freinet.de> <1995Nov20.125350.9627@friend.kastle.com> <1995Nov28.185702.4482@friend.kastle.com> <DItx1n.IrC@kroete2.freinet.de>
Date: Fri, 1 Dec 1995 12:40:23 GMT