offsetof

Header: <cstddef>

The macro offsetof expands to an integral constant expression of type std::size_t, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified subobject, including padding bits if any.

# Declarations

#define offsetof(type, member) /* implementation-defined */

# Notes

The offset of the first member of a standard-layout type is always zero (empty-base optimization is mandatory).

offsetof cannot be implemented in standard C++ and requires compiler support: GCC, LLVM.

member is not restricted to a direct member. It can denote a subobject of a given member, such as an element of an array member. This is specified by C DR 496.

It is specified in C23 that defining a new type containing an unparenthesized comma in offsetof is undefined behavior, and such usage is generally not supported by implementations in C++ modes: offsetof(struct Foo { int a, b; }, a) is rejected by all known implementations.

# Example

#include <cstddef>
#include <iostream>
 
struct S
{
    char   m0;
    double m1;
    short  m2;
    char   m3;
//  private: int z; // warning: 'S' is a non-standard-layout type
};
 
int main()
{
    std::cout
        << "offset of char   m0 = " << offsetof(S, m0) << '\n'
        << "offset of double m1 = " << offsetof(S, m1) << '\n'
        << "offset of short  m2 = " << offsetof(S, m2) << '\n'
        << "offset of char   m3 = " << offsetof(S, m3) << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
CWG 273C++98offsetof may not work if unary operator& is overloadedrequired to work correctly evenif operator& is overloaded
LWG 306C++98the behavior was not specified when type is not a PODTypethe result is undefined in this case
LWG 449C++98other requirements of offsetof wereremoved by the resolution of LWG issue 306added them back

# See also