Greffin28
Greffin28

Reputation: 257

Are variables declared side by side in a struct contiguous?

I know for sure that array elements are stored contiguously, but what if I declared something like this:

class A {
    public:
    int a, b, c;
    // or
    int a;
    int b;
    int c;
}

Are the members stored contiguously? I've been thinking if there's a possibility that a variable is stored in between the declaration of a and b from another process, so that it's not contiguous. But I'm not sure. Are there any guarantees?

Upvotes: 0

Views: 435

Answers (1)

M.M
M.M

Reputation: 141554

a b and c are guaranteed to be in that order in the struct.

However, in general, there might be structure padding in between any two struct members. Typically there would be no padding for a struct that only contained int members but it would be good practice to not make that assumption.

You could check this at compile-time:

static_assert( sizeof(A) == 3 * sizeof(int),  "oops, A had padding" );

Upvotes: 2

Related Questions