Search code examples
c++c++11stliteratorobject-layout

Do data members form a range?


Can I treat consecutive data members of the same type as a range? For example:

struct X
{
    int a, b, c, d, e;
};

X x = {42, 13, 97, 11, 31};

std::sort(&x.a, &x.a + 5);   // kosher?

Solution

  • No, this is undefined behaviour. You are treating x.a like the first element of an array, which it isn't. May work on some implementations, may raid your fridge too ;)