Sakshi Malhotra
Sakshi Malhotra

Reputation: 95

decoding the offset macro

I was trying to understand the offset macro in c and have a problem trying to interpret this

&((type *)0) in

#define offsetof(type, member) ((size_t) &((type *)0)->member)

How do I read it. I understood the functioning but not the exact interpretation of the term.

Thanks

Upvotes: 0

Views: 149

Answers (2)

EvgeniyZh
EvgeniyZh

Reputation: 905

Take look at this code:

type *x = 0;
size_t y = &x->member;

Normally, y would be equal x+offset, but because x=0, we get only offset.

In code we write ((type *)0) - directly returning pointer to 0 of type type, without creating x variable, then we take address of member ((type *)0)->member). All this is defined as size_t variable.

Upvotes: -2

3442
3442

Reputation: 8576

The expansion of this preprocessor macro:

#define offsetof(type, member) ((size_t) &((type *)0)->member)

Results in the following formal definition: The offsetof a given member on a given type is the casting to size_t of the address of the member member for the type located at the null pointer address.

Or, in other words, this is black magic that gets the address of member as if an object of type existed at the null pointer address (Note: there's no crash as long as no read or write occurs here). As the address of such a member is now absolute (relative to zero), its value can be safely casted to size_t, thus effectively evaluating to the offset of such a member as an absolute value.

Hope this helps!

Upvotes: 3

Related Questions