[lug] An unusual C construct

Anthony Foiani tkil at scrye.com
Tue Sep 21 20:39:47 MDT 2010


[catching up on weeks ... er, months ... of posts...]

Bear Giles <bgiles at coyotesong.com> writes:
>    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.  

Just to be clear, I think you meant to use a pointer variable for "tbl":

    tCLAIM_tbl_def * tblp = NULL;
    sizeof( tblp->acHealthService_id );

or a plain structure, which can't be initialized to NULL, and then use
the "." operator instead of "->":

    tCLAIM_tbl_def tbl;
    sizeof( tbl.acHealthService_id );

Either way, it might be nicer for maintenance programmers if the
original authors had used a macro:

    #define SIZEOF_STRUCT_MEMBER( STRUCT, MEMBER ) \
      sizeof( ( ( STRUCT * ) 0 )->MEMBER )

Something like this:

| #include <stdio.h>
| 
| typedef struct
| {
|     char c;
|     int i;
|     float f;
|     double d;
| } foo;
| 
| int
| main( int argc, char * argv [] )
| {
| 
| #define PRINT_SIZE( x ) \
|     printf( "sizeof( " #x " ) = %u\n", sizeof( x ) )
| 
|     PRINT_SIZE( ((foo *)0)->c );
|     PRINT_SIZE( ((foo *)0)->i );
|     PRINT_SIZE( ((foo *)0)->f );
|     PRINT_SIZE( ((foo *)0)->d );
| 
| #undef PRINT_SIZE
| 
| #define SIZEOF_STRUCT_MEMBER( STRUCT, MEMBER )  \
|     sizeof( ( ( STRUCT * ) 0 )->MEMBER )
| 
| #define PRINT_SSM( S, M )                               \
|     printf( "SIZEOF_STRUCT_MEMBER( " #S ", " #M " ) = %u\n", \
|             SIZEOF_STRUCT_MEMBER( S, M ) )
| 
|     PRINT_SSM( foo, c );
|     PRINT_SSM( foo, i );
|     PRINT_SSM( foo, f );
|     PRINT_SSM( foo, d );
| 
| #undef PRINT_SSM
| 
| #undef SIZEOF_STRUCT_MEMBER
| 
|     return 0;
| }

>    I've used it all the time with things like
>
>       sprintf(sizeof(tbl->name), "%s", tbl->name);

And just in case someone runs across this in the archive, that looks
like an odd call to 'sprintf'.  Maybe just:

    printf( "sizeof( %s ) = %u\n", "tblp->name", sizeof( tblp->name ) );

Anyway.

Happy hacking,
t.



More information about the LUG mailing list