typedef union UUID {
unsigned char byte[16]; /**< Array of 16 bytes. */
unsigned int ll[2]; /**< Array of two 64-bit words. */
} UUID;
struct EntryHeader {
UUID uuid; /**< UUID to which entry pertains. */
};
#define UUID_SELF {0,0,0,2}
int main(void)
{
struct EntryHeader entry;
entry.uuid = UUID_SELF;
}
The compiler complains thus
$ g++ union.cpp
union.cpp: In function ‘int main()’:
union.cpp:15:17: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
union.cpp:15:17: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
union.cpp:15:17: error: no match for ‘operator=’ in ‘entry.EntryHeader::uuid = {0, 0, 0, 2}’
union.cpp:1:20: note: candidate is: UUID& UUID:perator=(const UUID&)
How do I go about assigning values to this union in C++. Any help would be appreciated.
Note that array assignments are only supported by C++-11, not by C++-98.
Another note: Are you sure your compiler uses 64 bits for unsigned ints?
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
The answer is that in C++ you can only INITIALIZE the first 'member' of a union.
You can at any time ASSIGN any other 'member' of a union.
You can't assign initialiser lists (which is what you were trying to do)
It may not seem like a big deal, but when you are dealing with consts, it can be problematic, since you can't assign consts.
Code:
union uu
{
long l2[2];
char c8[8];
};
class UU
{
public:
uu u;
int i;
};
int main()
{
uu u = { 12,56 }; // Initializes the l2 portion of u with 12 and 56.
UU U = { 12,56, 5 }; // initializes the l2 portion of u with 12 and 56 and i with 5
}
If you flip l2 and c8 around in the uu union and don't change the rest of the code...
Code:
union uu
{
char c8[8]; // Now c8 if first
long l2[2];
};
class UU
{
public:
uu u;
int i;
};
int main()
{
uu u = { 12,56 }; // Initializes the c8 portion of u with 12 and 56, the remaining 6 c8's are aggregated to 0.
UU U = { 12,56, 5 }; // initializes the c8 portion of u with 12, 56 and 5, the remaining 5 c8's and i are aggregated to 0
// In this case you can 'force' a break by adding extra brackets.
UU U2 = { {12,56}, 5 }; // Initialize the c8 portion of 8 with 12 and 56, aggregates the remaining 6 to 0, and initialises i with 5.
}
Last edited by OReubens; September 13th, 2012 at 11:08 AM.
Bookmarks