INFO: Initializing Unions Initializes First Member of the Union
This article was previously published under Q47693 On This PageSUMMARY
When initializing a union, the initialization value is applied to the first
member of the union even if the type of the value matches a subsequent
member. As stated in the ANSI Standard, Section 3.5.7:
Because you cannot initialize the value of any member of a union other than
the first one, you must assign their values in a separate statement.
Initializing a union with a value intended for a subsequent member causes
that value to be converted to the type of the first member.
MORE INFORMATION
The following example demonstrates the issue:
Sample Code
The output from the example, though not what is intended, is as
follows:
test.a = 3, test.b = 0.00000To associate a value with "b", you can reverse the order of the members, as in the following:
Or, you can retain the order of the elements and assign the value in a
separate statement, as in the following:
Either of these methods creates the following output:
test.a = 26214, test.b = 3.600000Under Windows NT, the output would be as follows: test.a = 1080452710, test.b = 3.600000 REFERENCES
For examples and explanation of possible compiler errors and warnings
generated when attempting to initialize a non-primary union element, please
see the following article in the Microsoft Knowledge Base:
39910 (http://support.microsoft.com/kb/39910/EN-US/) PRB: Initializing Non-Primary Union Element Produces Errors
APPLIES TO
|
Back to the top