offsetof - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# offsetof

From cppreference.com
< cpp‎ | types

Defined in header `<cstddef>` |  |
#define offsetof(type, member) /*implementation-defined*/ |  |

The macro offsetof expands to a constant 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.

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)

### [edit] Possible implementation

    #define offsetof(type,member) ((std::size_t) &(((type*)0)->member))

### [edit] Example

Run this code

    #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

### [edit] See also

size_t | unsigned integer type returned by the `sizeof` operator (typedef) [edit]
is_standard_layout (C++11) | checks if a type is standard-layout type (class template) [edit]
C documentation for offsetof

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/types/offsetof&oldid=70955"