I have the following type definition:
typedef union{
unsigned int Entry;
struct {
unsigned char EntryType;
unsigned char EntryOffset[3];
};
} TLineDescriptor;
I also have the following use of the type:
TLineDescriptor LineDescriptor;
LineDescriptor.Entry = 40;
LineDescriptor.EntryType = 0x81;
sizeof(LineDescriptor) shows that this variable occupies 4 bytes of memory, which at first I assumed that it either held the int or the struct.
cout << LineDescriptor.Entry << " " << LineDescriptor.EntryType << endl;
However, the line above prints two different values, namely 129 ü, LineDescriptor.Entry is apparently referring to the memory location where the value 0x81 was saved. I’m not sure what happened with the 40.
But it is clear that my assumption was wrong. Can someone interpret and explain the type definition properly? Understanding it is crucial for me to working with the code I found.
Thank you in advance.
These are not different values, actually.
129is the character code for the characterü. Theoperator <<of theostreamtreatsintandchardata types differently, printing the numerical value for the first one and the character value for the latter one.So, your understanding of union types are correct. However, note that endianness could be an issue when dealing with union types. For example, on little-endian machines
EntryTypewill hold the least significant byte ofEntryand theEntryOffsetarray the others. But on big-endian machines,EntryTypewill hold the most significant byte.