curiosity: structure assignments in C (and unions within structs)

N

Neil Zanella

Hello,

In C++ AFAIK structure assignment copies every data member element by
element. This rule also works with the gcc 3.2.2 C compiler and even
works when one of the members is a union as in the following example
but I would like to know whether this is a gcc extension or whether
it's actually part of the C99 standard. Did previous C standards
allow this?

#include <stdio.h>

struct Foo { int a; int b; union { int x; float y; } z; };

int main(void) {
struct Foo hello = { 1, 2 }; /* OK */
hello.z.y = 1.1; /* OK */
printf("%f\n", hello.z.y); /* OK */
struct Foo hell = hello; /* OK */
printf("%d\n", hell.a); /* OK */
printf("%d\n", hell.b); /* OK */
printf("%f\n", hell.z.y); /* OK */
return 0;
}

Thanks,

Neil
 
J

Jack Klein

Hello,

In C++ AFAIK structure assignment copies every data member element by
element. This rule also works with the gcc 3.2.2 C compiler and even
works when one of the members is a union as in the following example
but I would like to know whether this is a gcc extension or whether
it's actually part of the C99 standard. Did previous C standards
allow this?

#include <stdio.h>

struct Foo { int a; int b; union { int x; float y; } z; };

int main(void) {
struct Foo hello = { 1, 2 }; /* OK */
hello.z.y = 1.1; /* OK */
printf("%f\n", hello.z.y); /* OK */
struct Foo hell = hello; /* OK */
printf("%d\n", hell.a); /* OK */
printf("%d\n", hell.b); /* OK */
printf("%f\n", hell.z.y); /* OK */
return 0;
}

Thanks,

Neil

No version of the C standard specifies how structures or unions are
copied. The only guarantee is that after the copy, they will compare
equal by suitable member-by-menber comparisons. There is no guarantee
that they will be identical as determined by memcmp().

Or are you asking whether C has structure and union assignments? For
almost 10 years before there was a C++ standard.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top