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

Łukasz Szczur via cfe-users cfe-users at lists.llvm.org
Mon Mar 12 17:14:51 PDT 2018


 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.html>


More information about the cfe-users mailing list