stddef.h offsetof

Programming, for all ages and all languages.
Post Reply
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

stddef.h offsetof

Post by Neo »

The following macro is defined in stddef.h

Code: Select all

#define offsetof(s,memb) ((size_t)((char *)&((s *)0)->memb-(char *)0))
Couldn't this be replaced with the following

Code: Select all

#define offsetof(s,memb) ((size_t)((char *)&((s *)0)->memb))
// no - (*char *)0
Only Human
Ytinasni

Re:stddef.h offsetof

Post by Ytinasni »

This will work on any compiler where

1) the NULL pointer is the bit pattern of all zeroes, and
2) casting a pointer to a size_t gives the same bit representation as the pointer

The C standard requires neither of those to be true, AFAIK.

Having said that, those are both true for most, if not all, compilers targetting x86 and AMD64, as well as those for most other architectures.

In conclusion, you might be able to do that, but its a bad idea if you want your code to be portable to other compilers and/or architectures.
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:stddef.h offsetof

Post by Solar »

Ytinasni wrote: The C standard requires neither of those to be true, AFAIK.
Correct.
Every good solution is obvious once you've found it.
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

Re:stddef.h offsetof

Post by Neo »

I am seeing the following lint warning with this which I think is caused by the offsetof().
Is there anything that can be done to overcome this in the code (other than adding a lint comment that is).
    getRg(offsetof(LAPI_RS, medPrm)) )
svcPrm.cpp 33 Warning 413: Likely use of null pointer 'unknown-name' in left argument to operator '->' [Reference: file svcPrm.cpp: line 33]
Where LAPI_RS is a struct and medPrm a member in it.
Any ideas would be greatly appreciated.
Only Human
User avatar
Pype.Clicker
Member
Member
Posts: 5964
Joined: Wed Oct 18, 2006 2:31 am
Location: In a galaxy, far, far away
Contact:

Re:stddef.h offsetof

Post by Pype.Clicker »

The 'offsetof()' thing make uses of null pointer expressions (and pretty on purpose).

Now, i see nothing that could prevent you of using any kind of symbol instead of NULL (e.g. &((_struct*)main)->_field could do the trick as well), provided that you find a suitable symbol (void* most preferably to avoid type casting warnings)...
Post Reply