Assigning values to union C++

Hello

I have a union of this type

typedef union UUID {
uint8 byte[16]; /**< Array of 16 bytes. */
uint64 ll[2]; /**< Array of two 64-bit words. */
} UUID;

struct EntryHeader {
UUID uuid; /**< UUID to which entry pertains. */
<blah>
}

And I assign values like this

#define UUID_SELF ((UUID) {.byte = {0,0,0,2}})
EntryHeader entry;
entry.uuid = UUID_SELF

This code compiles fine if used in a C file, but if used in a C++ file, the compiler complains of the following..

error: extended initializer lists only available with -std=c++0x or -std=gnu++0x

Enabling -std=c++0x is not an option as that would open up an entirely new can of worms. Any pointers as to what would help here?

Thanks
-Pranava
Remove .byte =

According to the C++ standard

15 When a union is initialized with a brace-enclosed initializer, the braces shall only contain an initializer-clause for the first non-static data member of the union.


Also (UUID) shall not be present.
Last edited on
Thanks vlad, but I guess the problem manifested in a different way now. I do this

typedef union UUID {
uint8 byte[16]; /**< Array of 16 bytes. */
uint64 ll[2]; /**< Array of two 64-bit words. */
} UUID;

struct EntryHeader {
UUID uuid; /**< UUID to which entry pertains. */
<blah>
}

#define UUID_SELF {0,0,0,2}
EntryHeader entry;
entry.uuid = UUID_SELF;

and the compiler complains thus.

error: extended initializer lists only available with -std=c++0x or -std=gnu++0x
error: extended initializer lists only available with -std=c++0x or -std=gnu++0x
error: no match for 'operator=' in 'tableEntry->EntryHeader::uuid = {0, 0, 0, 2}'
note: candidates are: UUID& UUID::operator=(const UUID&)

Am I missing something again?
You may not do that

EntryHeader entry;
entry.uuid = UUID_SELF;

because the last statement is not an initialization.

try the following

EntryHeader entry = { UUID_SELF };
Last edited on
Initialization of the variable during declaration seems to work as you described. Is there a way to actually assign a value to entry.uuid later (not during initialization)? the reason is EntryHeader does contain other fields too and I will not be able to initialize all of them during init time..
Thanks for the help vlad
-Pranava
If your compiler supports C++ 2011 then you can try

entry.uuid.byte = UUID_SELF;

Last edited on
> Enabling -std=c++0x is not an option as that would open up an entirely new can of worms.
> Any pointers as to what would help here?

Use the compiler instead of the preprocessor.

1
2
//#define UUID_SELF {0,0,0,2}
const UUID UUID_SELF = {0,0,0,2} ;


And then, either:
1
2
EntryHeader entry ;
entry.uuid = UUID_SELF ;

or: EntryHeader entry = { UUID_SELF /*, .... */ } ;
Thanks JLBorges
that did help.
-P
Topic archived. No new replies allowed.