Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

offsetof — a member's offset within an object

The offsetof macro from <cstddef> determines a member's byte offset from the beginning of an object. It supports memory-layout checks, but portable use requires a standard-layout type.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <cstddef>
offsetof(type, member-designator)

offsetof(type, member-designator) from <cstddef> produces an integer constant expression of type std::size_t: the designated member's byte offset from the beginning of an object. Its arguments are a type and a member designator, not an object instance. It is a macro; write offsetof, not std::offsetof.

For portable use, choose a standard-layout type. Support for other class types is conditional: an implementation need not provide it. Applying it to a static data member or member function has undefined behavior. Do not apply it to bit-fields. A valid invocation does not throw exceptions.

Alignment can introduce padding bytes between members. Therefore, do not assume an offset equals the sum of preceding members' sizes or has the same value across platforms. offsetof alone does not provide a portable serialization format.

The example checks std::is_standard_layout_v<Record> and computes offset at compile time. Instead of printing a platform-dependent number, it tests a guaranteed relationship: value is located after tag. The expected output is true followed by a newline.

Examples

#include <cstddef>
#include <iostream>
#include <type_traits>

struct Record {
    char tag;
    int value;
};

static_assert(std::is_standard_layout_v<Record>);
constexpr std::size_t offset = offsetof(Record, value);
static_assert(offset >= sizeof(char));
static_assert(noexcept(offsetof(Record, value)));

int main() {
    std::cout << std::boolalpha
              << (offset >= sizeof(char)) << '\n';
}

Result

true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources