[cfe-users] Undefined behaviour in a small code snippet

2018-03-19 Thread Łukasz Szczur via cfe-users
 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

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;
}
___
cfe-users mailing list
cfe-users@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-users


Re: [cfe-users] Undefined behaviour in a small code snippet

2018-03-19 Thread Matthew Fernandez via cfe-users
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  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 
> To: cfe-users@lists.llvm.org
> Subject: [cfe-users] Undefined behaviour in a small code snippet
> Message-ID:
>
> 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
> 
> 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: 
> 
> 
> --
> 
> 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