[lug] An unusual C construct

Bear Giles bgiles at coyotesong.com
Thu Jul 29 08:20:15 MDT 2010


It's nothing special to the compiler.

   sizeof(((tCLAIM_tbl_def *)0x0)->acHealth_Service_Id)

is going to be parsed in the same way as

   tCLAIM_tbl_def tbl = NULL;

   sizeof(tbl->acHealthService_id)

which wouldn't be an issue at all.  I've used it all the time with things
like

   sprintf(sizeof(tbl->name), "%s", tbl->name);

Using a null pointer is weird since you normally have that object lying
around somewhere if you need the size of a component of it, but I could
imagine someone who doesn't grok the details thinking it's more secure to
not reference a live object.

On Thu, Jul 29, 2010 at 12:07 AM, Kenneth D Weinert
<kenw at quarter-flash.com>wrote:

> On 07/28/2010 11:46 PM, David Morris wrote:
> > On Wed, Jul 28, 2010 at 22:57, Kenneth D Weinert<kenw at quarter-flash.com>
>  wrote:
>
> >> It's nothing I need to change - I'd just like to understand how it works
> :)
> >
> > The reason this works (If I recall correctly) is that "sizeof" is an
> > operator which is calculated at compile time.
>
> Yep, that part I knew - I wasn't concerned about actually dereferencing
> the pointer at run time.
>
> > Yes it looks weird to
> > be apparently dereferencing a NULL pointer, but that code is never
> > actually executed...when the code runs, that entire statement has
> > already been changed to the size of acHealth_Service_Id within that
> > structure.  Basically it is the (ugly) C equivalent of the C++
> > statement "sizeof(tCLAIM_tbl_def::acHealth_Service_Id)".
>
> It's just not clear to me how the compiler "does the right thing". I'm
> presuming it's some sort of idiom that just works because it does :)
>
> It's always interesting when you start a new job and see a new body of
> code and try to understand how other people think.
>
> Thanks for discussion.
> --
> Ken Weinert
> _______________________________________________
> Web Page:  http://lug.boulder.co.us
> Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
> Join us on IRC: irc.hackingsociety.org port=6667 channel=#hackingsociety
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20100729/2c1c6268/attachment.html>


More information about the LUG mailing list