By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,002 Members | 1,286 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,002 IT Pros & Developers. It's quick & easy.

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

P: n/a

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

Nov 13 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On Tue, 16 Sep 2003 23:59:06 -0230, Neil Zanella <nz******@cs.mun.ca>
wrote in comp.lang.c:

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
Nov 13 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.