-1

Possible Duplicate:
Why does this C code work?

I do see a macro defined to compute the structure offset as follows

#define offsetof(st, m) ((size_t)(&((st *)0)->m))

But I don't get on how this definition works. It looks like a member of structure is accessed via a NULL pointer. Can any one please elaborate how this expression works?

Community
  • 1
  • 1
Vivek Maran
  • 2,623
  • 5
  • 38
  • 52

2 Answers2

1

This expression is optimized in compile-time, resulting into a compile-time offset value in your program.

Compiler sees a constant pointer (0), sees a constant offset from it and just applies constant folding, producing the address 0 + offset (== offset), which is what we need.

It's interesting whether this works without any optimizations or some basic constant folding is done always.

P.S. More precisely this optimization is called Scalar Replacement of Aggregates, as was pointed out by Lei Mou below.

Dmytro Sirenko
  • 5,003
  • 21
  • 26
  • Thank you for pointing out that this is due to compiler optimization. However, from what I tried with clang and opt, the pass "Scalar Replacement of Aggregates" actually transform this macro into a constant. – Lei Mou Dec 12 '12 at 13:00
  • @LeiMou Yes, it's more precise name for this optimization. I've just applied my knowledge from 'Compilers' at Coursera to give a name to this behavior :) – Dmytro Sirenko Dec 12 '12 at 13:03
1

1) First a null pointer to a structure of type 'st' is created: (st *)0

2) Next the member of of this structure is taken: ->m

3) Next the address of the member is taken: &(...)

4) Finally the address of the member is cast to a size-t type: (size_t)(...)

The work happens at step 3, as the pointer is null (i.e. address == 0) then the address off the member simply contains the members position within the structure.

Crog
  • 1,112
  • 8
  • 16