offsetof

< cpp‎ | types
 
 
 
Type support
Basic types
Fundamental types
Fixed width integer types (C++11)
(C++11)
offsetof
Numeric limits
C numeric limits interface
Runtime type information
Type traits
Type categories
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Type properties
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)(until C++20)
(C++11)(deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Endian
(C++20)
Constant evaluation context
Supported operations
Relationships and property queries
(C++11)
(C++11)
Type modifications
(C++11)(C++11)(C++11)
Type transformations
(C++11)
(C++11)
(C++17)
(C++11)(until C++20)(C++17)
 
Defined in header <cstddef>
#define offsetof(type, member) /*implementation-defined*/

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 member, including padding if any.

If type is not a standard layout type, the behavior is undefined (until C++17)use of the offsetof macro is conditionally-supported (since C++17).

If member is a static member or a member function, the behavior is undefined.

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

The expression offsetof(type, member) is never type-dependent and it is value-dependent if and only if type is dependent.

Exceptions

offsetof throws no exceptions; the expression noexcept(offsetof(type, member)) always evaluates to true.

Notes

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

Example

#include <iostream>
#include <cstddef>
struct S {
    char c;
    double d;
};
int main()
{
    std::cout << "the first element is at offset " << offsetof(S, c) << '\n'
              << "the double is at offset " << offsetof(S, d) << '\n';
}

Possible output:

the first element is at offset 0
the double is at offset 8

See also

unsigned integer type returned by the sizeof operator
(typedef)
checks if a type is a standard-layout type
(class template)