Re: offsetof
- From: Flash Gordon <spam@xxxxxxxxxxxxxxxxxx>
- Date: Fri, 30 Sep 2005 11:40:34 +0100
junky_fellow@xxxxxxxxxxx wrote:
luke wrote:
hi all, i have another question. I've read the FAQ regarding my former question (sizeof struct and union) and in question 2.14 it talks about offset macro.
This is good. Not just your reading the FAQ, but also telling us you have read the relevant section. I wish more people would do as you have done and read the FAQ and then tell us.
#define offsetof(type, mem) ((size_t) \ ((char *)&((type *)0)->mem - (char *)(type *)0))
Can anyone explain me how it works. 1)I can't understand what "0" casted to (type *) means 2)Isn't the second menber of substraction "(char *)(type *)0" useless?
The second member of sustraction would be required on implementation where the NULL pointer is *not* represented by all-bits-zero.
That is part of it. It also avoids the issue of how pointers are converted to integers. For example, I believe that on the Cray implementation of C the offset of a byte within a 64 bit word is actually stored in the high bits of a char pointer. Pointer subtraction obviously has to allow for this, but converting a pointer to an integer does not (although it could).
On some system it may well be defined as the far simpler
#define offsetof(type, mem) ((size_t)&((type *)0)->mem)
because the implementer has chosen to do things in such a way that this works.
Probably, this is why offsetof macro is implementation specific.
Yes, the way the offsetof macro is implemented is implementation specific because for some implementations it needs to use strange tricks to work (on all implementation is has to use some tricks, but not always strange ones). Obviously the author of the implementation can make any strange trick they want work and then use it, but someone using the implementation can't use such tricks because they either invoke undefined behaviour or implementation defined behaviour and so could do anything on another system.
If you (or luke) looks in the system headers for your implementation you will find lots of other non-portable tricks being used, which is why it is not generally worth looking in the system headers to see how things are done.
This is also why you should use the facilities provided by the implementation rather than trying to roll your own.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
.
- Follow-Ups:
- Re: offsetof
- From: junky_fellow
- Re: offsetof
- References:
- offsetof
- From: luke
- Re: offsetof
- From: junky_fellow
- offsetof
- Prev by Date: Re: A[x][y][z]
- Next by Date: Re: Assembler vs Compiler vs Linker
- Previous by thread: Re: offsetof
- Next by thread: Re: offsetof
- Index(es):
Relevant Pages
|