5
votes

I came across the initial sequence concept. Serching through the Standard for initial sequence phrase gives only 3 results and they don't give a definition.

Section N3797::9.5/1 [class.union]:

If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members;

I wish to look at an example which is demostrated that quote.

1
What prevents you from just writing up an example? key phrase "standard-layout union type contains one of the standard-layout structs"Cheers and hth. - Alf
@Cheersandhth.-Alf What's the initial sequnce?user2953119
I think it is saying that for as long as the data members are of the same type, the padding between them will be the same and the members will properly alias one another. That means putting a number in using one struct's identifier can be accurately gotten out (from the same position) using a different struct's identifier until one of the structs contains a different type (in declaration order) to the other. (Is that explanation less complicated than the docs?)!Galik
the key-phrase here is common initial sequence, the common part is important, if all struct's start with int kind; then thats the common initial sequence.sp2danny
@DmitryFucintv According to my understading your example causes no UB. But that guarantee ends as soon as the types differ in declaration order.Galik

1 Answers

6
votes

I believe it's talking about this kind of thing:

union U {
    struct S {
        int a;
        int b;
        int c;
    }
    struct T {
        int x;
        int y;
        float f;
    }
};

It's saying that it's OK to access either U.S.a or U.T.x and that they will be equivalent. Ditto for U.S.b and U.T.y of course. But accessing U.T.f after setting U.S.c would be undefined behaviour.