Alex Rivera | Logout

What is the purpose and return type of the __builtin_offsetof operator?

Asked 2008-12-30T12:04:23.283
18

What is the purpose of __builtin_offsetof operator (or _FOFF operator in Symbian) in C++?

In addition what does it return? Pointer? Number of bytes?

Edit
Report

1 Answer

17

It's a builtin provided by the GCC compiler to implement the offsetof macro that is specified by the C and C++ Standard:

GCC - offsetof

It returns the offset in bytes that a member of a POD struct/union is at.

Sample:

struct abc1 { int a, b, c; };
union abc2 { int a, b, c; };
struct abc3 { abc3() { } int a, b, c; }; // non-POD
union abc4 { abc4() { } int a, b, c; };  // non-POD

assert(offsetof(abc1, a) == 0); // always, because there's no padding before a.
assert(offsetof(abc1, b) == 4); // here, on my system
assert(offsetof(abc2, a) == offsetof(abc2, b)); // (members overlap)
assert(offsetof(abc3, c) == 8); // undefined behavior. GCC outputs warnings
assert(offsetof(abc4, a) == 0); // undefined behavior. GCC outputs warnings

@Jonathan provides a nice example of where you can use it. I remember having seen it used to implement intrusive lists (lists whose data items include next and prev pointers itself), but I can't remember where it was helpful in implementing it, sadly.

answered 2008-12-30T12:11:11.337

Your Answer