public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
From: "Łukasz Szczur" <luks.sfm@gmail.com>
To: gcc-help@gcc.gnu.org
Subject: Undefined behaviour in a small code snippet
Date: Tue, 13 Mar 2018 00:10:00 -0000	[thread overview]
Message-ID: <CADW1ASSOf3gu41WdVbc9wnCd2K0cv9KxYP8cn2K0W=FxWqTzmg@mail.gmail.com> (raw)

 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;
}

                 reply	other threads:[~2018-03-13  0:10 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to='CADW1ASSOf3gu41WdVbc9wnCd2K0cv9KxYP8cn2K0W=FxWqTzmg@mail.gmail.com' \
    --to=luks.sfm@gmail.com \
    --cc=gcc-help@gcc.gnu.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).