Within an array, pointer arithmetic is allowed (as long as the result doesn't exceed the bounds, where the end bound is one past the end of the array).
// Legit
int m[3] = {0, 1, 2};
int const *p = m;
std::cout << *p << *(p + 1) << *(p + 2) << std::endl;
Does the standard allow pointer arithmetic like this with a standard layout struct that contains consecutive member variables of the same fundamental type?
// Well defined???
struct MyStruct {
int a, b, c;
};
static_assert(std::is_standard_layout_v<MyStruct>);
MyStruct m = {0, 1, 2};
int const *p = &m.a;
std::cout << *p << *(p + 1) << *(p + 2) << std::endl;
I certainly can compare pointers to the individual variables (i.e., &m.a < &m.b
) because they are members of the same object, but I cannot determine whether &m.a+1
is guaranteed to be &m.b
.
I know this will likely work with most compilers, but I'm curious about what the standard says (C++20, if it matters).