[cfe-users] Undefined behaviour in a small code snippet
Matthew Fernandez via cfe-users
cfe-users at lists.llvm.org
Mon Mar 19 18:28:12 PDT 2018
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 at lists.llvm.org> wrote:
>
> Send cfe-users mailing list submissions to
> cfe-users at 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-request at lists.llvm.org
>
> You can reach the person managing the list at
> cfe-users-owner at 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 at lists.llvm.org>
> To: cfe-users at lists.llvm.org
> Subject: [cfe-users] Undefined behaviour in a small code snippet
> Message-ID:
> <CADW1ASR2he1C2YD+v8bE5yysgFMFi7jzCoszW2H_VYM2EBNPdg at 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 at lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-users
>
>
> ------------------------------
>
> End of cfe-users Digest, Vol 62, Issue 9
> ****************************************
More information about the cfe-users
mailing list