union test
{
int i;
char ch;
}t;
int main()
{
t.ch=20;
}
Suppose sizeof(int)==2 and let the memory addresses allocated for t are 2000, 2001.
Then where is 20 i.e. t.ch stored – at 2000 or 2001 or depends on endianness of machine?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The C99 standard (§6.7.2.1.14) says:
(emphasis added)
The bold statement actually says that each member of the union has the same address, so they all “begin” at the same address.
t, ast.chast.i, should be at address 2000, thust.choverlaps with the first byte (in address order) oft.i.What this means in terms of “what do I get if I try to read
t.iafter settingt.c” in the real world depends on platform endianness, and in facts trying to read a member of a union when you wrote in another one is Unspecified Behavior according to the C standard (§6.2.6.1.6/7, restated at §J.1.1).What helps more to understand the endianness of the machine (at least, I think it’s more straightforward to understand) is to have a union like this:
doing
and then looking what’s inside the two chars at
t.ch. If you are on a little-endian machine you’ll gett.ch[0]==20andt.ch[1]==0, and the opposite if you’re on a big-endian machine (ifsizeof(int)==2). Notice that, as already said, this is an implementation specific detail, the standard does not even mention endianness.To make it even clearer: if you have a 2-byte
intvar set to 20, on a little-endian machine, dumping the memory associated to it in address-order, you’ll get (in hexadecimal representation, bytes split by space):while on a big-endian machine you’ll get
The big-endian representation looks “more right” from our point of view, because in the little endian representation the bytes that make the whole
intare stored in reverse order.Yes, here it does, but in your question you’re asking another thing; this looks more my example.