I don’t have the reference on hand, but I’m pretty sure writing to one union 
member and reading the value back through another is undefined behaviour. I 
believe this is inherited from C99 or earlier. 

> On 19 Mar 2018, at 12:00, via cfe-users <cfe-users@lists.llvm.org> wrote:
> 
> Send cfe-users mailing list submissions to
>    cfe-users@lists.llvm.org
> 
> To subscribe or unsubscribe via the World Wide Web, visit
>    http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-users
> or, via email, send a message with subject or body 'help' to
>    cfe-users-requ...@lists.llvm.org
> 
> You can reach the person managing the list at
>    cfe-users-ow...@lists.llvm.org
> 
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of cfe-users digest..."
> 
> 
> Today's Topics:
> 
>   1. Undefined behaviour in a small code snippet
>      (Łukasz Szczur via cfe-users)
> 
> 
> ----------------------------------------------------------------------
> 
> Message: 1
> Date: Tue, 13 Mar 2018 01:14:51 +0100
> From: Łukasz Szczur via cfe-users <cfe-users@lists.llvm.org>
> To: cfe-users@lists.llvm.org
> Subject: [cfe-users] Undefined behaviour in a small code snippet
> Message-ID:
>    <cadw1asr2he1c2yd+v8be5yysgfmfi7jzcoszw2h_vym2ebn...@mail.gmail.com>
> Content-Type: text/plain; charset="utf-8"
> 
> Hello,
> 
> The program at the bottom prints
> 1
> 2
> 1
> 2
> 
> Does the code contain undefined behaviour in C++17 (note that the structs
> have common initial sequence )?
> 
> Łukasz
> 
> 
> #include<iostream>
> 
> using namespace std;
> 
> struct A {
>    int first;
>    int second;
> };
> 
> struct B {
>    int first;
>    int second;
> };
> 
> struct Test {
>    union {
>        A a;
>        B b;
>    };
> };
> 
> int main() {
>    Test t;
>    t.a.first = 1;
>    t.b.second = 2;
>    cout << t.a.first << '\n';
>    cout << t.a.second << '\n';
>    cout << t.b.first << '\n';
>    cout << t.b.second << '\n';
>    return 0;
> }
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: 
> <http://lists.llvm.org/pipermail/cfe-users/attachments/20180313/89f47154/attachment-0001.html>
> 
> ------------------------------
> 
> Subject: Digest Footer
> 
> _______________________________________________
> cfe-users mailing list
> cfe-users@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-users
> 
> 
> ------------------------------
> 
> End of cfe-users Digest, Vol 62, Issue 9
> ****************************************
_______________________________________________
cfe-users mailing list
cfe-users@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-users

Reply via email to