Re: different way of finding out offsetof a member in structure



On Mon, 5 Nov 2007 18:59:41 +1000, "MisterE" <MisterE@xxxxxxxxx> wrote
in comp.lang.c:


<abhimanyu.v@xxxxxxxxx> wrote in message
news:1194249397.600624.89570@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi Guys,

I have one doubt. The test program is given below. It uses two way of
finding out the offset of a variable in structure. I executed the
program and found the same result.

My question is what is difference between

1) (unsigned long) &((struct foobar *)0)->foo
and
2) (unsigned long)((char*)&tmp.boo - (char*)&tmp)

? I assume you know the difference. The 0 one is just assigning the pointer
value 0 (Address 0) and the compiler does the offset from the struct.

I have to assume that you don't know much about C. Assigning 0 to a
pointer creates a null pointer, which does not point to address 0, and
may not be all bits 0 in its representation.

The first one can load the value 0 to a reigster as a direct value. The 2nd
one cannot load its values directly because they are variable.
The second one also uses a subtraction operation.
The difference is that the first one is going to require less machine
instructions and will execute faster.

....the real difference is that the first one produces undefined
behavior and is completely non-portable.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
.



Relevant Pages

  • Re: different way of finding out offsetof a member in structure
    ... The test program is given below. ... but because evaluating the expression performs ... addition to a null pointer, ... It also assumes that you can add an offset to a null pointer, ...
    (comp.lang.c)
  • Re: different way of finding out offsetof a member in structure
    ... The test program is given below. ... The 0 one is just assigning the pointer ... but in this case its a restricted memory architecture. ...
    (comp.lang.c)
  • "combined" pointers or "linear" pointers ??? >D
    ... Ok now I am on a quest to find out the truth lol:) ... "Oh that will be simple, I'll just write a test program and test ... "linear" pointer type. ... (Maybe it is because the pointer's offset wrapped, ...
    (alt.comp.lang.borland-delphi)
  • Re: offsetof() macro
    ... > To my untrained eye that would basically result in a null pointer. ... The offsetofmacro is "special", as are many other things in the ... the structure definition, they know the offset of the first member, ... And the compiler ...
    (comp.lang.c)
  • Re: Silly new instructions
    ... what you have is a pointer or integer. ... - Pointers are always intervals of memory addresses, ... The tag bit in the second word ... interval plus offset. ...
    (comp.arch)