C++ Standard Library C++ STL Library

C++ <cstddef> - offsetof



The C++ <cstddef> offsetof macro expands to an integral constant expression of type size_t, the value of which is the offset, in bytes, between the specified member and the beginning of its structure.

Syntax

offsetof(type, member)           

Parameters

type

Specify a type in which member is a valid member designator.

  • Until C++11: type shall be a POD class (Plain Old Data type, compatible with the types used in the C programming language and can be exchanged with C libraries directly).
  • Since C++11: type shall be a standard-layout class.
member Specify a member of type.

Return Value

Returns a value of type size_t with the offset value of member in type.

Example:

The example below shows the usage of offsetof macro function.

#include <cstdio>
#include <cstddef>

struct foo {
  char a;
  char b[10];
  char c;
};

int main () {
  printf("offsetof(struct foo, a) is %zu\n", offsetof(struct foo, a));
  printf("offsetof(struct foo, b) is %zu\n", offsetof(struct foo, b));
  printf("offsetof(struct foo, c) is %zu\n", offsetof(struct foo, c));
  return 0;
}

The output of the above code will be:

offsetof(struct foo, a) is 0
offsetof(struct foo, b) is 1
offsetof(struct foo, c) is 11

❮ C++ <cstddef> Library