[lug] An unusual C construct

David Morris lists at morris-clan.net
Wed Jul 28 23:46:02 MDT 2010


On Wed, Jul 28, 2010 at 22:57, Kenneth D Weinert <kenw at quarter-flash.com> wrote:
>
> sizeof(((tCLAIM_tbl_def *)0x0)->acHealth_Service_Id)
>
> tCLAIM_tbl_def is a structure typedef.
>
> I understand the intent of this code - it's to get the size of the
> field in the tCLAIM_tbl_def structure so the equivalent field in the
> current structure (not shown) can be the same size.
>
> It's just that in all my years of coding C I've never seen this
> technique used. It does work, at least on the AIX compiler we're using
> here.
>
> I'll also note that it's hard to google - at least I've not come up
> with the correct search terms to find an explanation.
>
> 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.  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)".

> They also have the habit of passing in a pointer and using it like:
>
> ptr[0].field

I've seen this type of construct a lot from people who have never seen
pointers before and don't understand what they are (the most common
misconception I've encountered is that a pointer is simply a form of
declaring an array).  Then once that construct exists in the code at
all, it tends to propagate, even if other coders should know better.

David



More information about the LUG mailing list