N
Neil Zanella
Hello,
I would like to know what the C standards (and in particular the C99
standard) have to say about union initializers with regards to the
following code snippet (which compiles fine under gcc 3.2.2 but
does not produce the expected results, the expected results
being the ones annotated in the comments in the code):
#include <stdlib.h>
union Foo {
struct {
int y1;
union {
int z1;
float z2;
} y2;
} x;
void *a;
};
int main(void) {
union Foo foobar1 = { { 1, { 22 } } };
union Foo foobar2 = { { 2, { 33.1 } } };
/* expecting 1, OK */
printf("foobar1: %d\n", foobar1.x.y1);
/* expecting 22, OK */
printf("foobar1: %d\n", foobar1.x.y2.z1);
/* expecting 2, OK */
printf("foobar2: %d\n", foobar2.x.y1);
/* expecting 33.1, not 0.00 */
printf("foobar2: %f\n", foobar2.x.y2.z2);
}
I would have thought, that seeing that 33.1 is a float and not an
integer, the float would have been properly stored in the union.
What does the standard say about the above code; is any of it
illegal or is any of it subject to implementation dependent
behavior, and if so then why didn't gcc complain?
Thank you for your clarifications,
Neil
I would like to know what the C standards (and in particular the C99
standard) have to say about union initializers with regards to the
following code snippet (which compiles fine under gcc 3.2.2 but
does not produce the expected results, the expected results
being the ones annotated in the comments in the code):
#include <stdlib.h>
union Foo {
struct {
int y1;
union {
int z1;
float z2;
} y2;
} x;
void *a;
};
int main(void) {
union Foo foobar1 = { { 1, { 22 } } };
union Foo foobar2 = { { 2, { 33.1 } } };
/* expecting 1, OK */
printf("foobar1: %d\n", foobar1.x.y1);
/* expecting 22, OK */
printf("foobar1: %d\n", foobar1.x.y2.z1);
/* expecting 2, OK */
printf("foobar2: %d\n", foobar2.x.y1);
/* expecting 33.1, not 0.00 */
printf("foobar2: %f\n", foobar2.x.y2.z2);
}
I would have thought, that seeing that 33.1 is a float and not an
integer, the float would have been properly stored in the union.
What does the standard say about the above code; is any of it
illegal or is any of it subject to implementation dependent
behavior, and if so then why didn't gcc complain?
Thank you for your clarifications,
Neil