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

union access

P: n/a
typedef struct ntt {
int type;
union {
int i;
char* s;
};
}nt;

nt n;
n.i = 0;

I found a C example like this and could not get gcc 2.95.4 to compile it
(struct has no member named `i') until I declared an instance of the union:
union {
int i;
char* s;
}u;

and accessed like:
n.u.i = 0;

Is the first example valid? If so, where is the problem?

--
Sean Dolan
Nov 14 '05 #1
Share this Question
Share on Google+
73 Replies


P: n/a
Sean Dolan wrote:
typedef struct ntt {
int type;
union {
int i;
char* s;
};
}nt;


This is called an anonymous union and it is a Microsoft extension. While
gcc supports MS extensions with the flag -fms-extensions, you'd do
better converting it to standard C. You can do this as you suggested. If
you want to avoid fixing up all references, you can simply dispose of
the union, costing an extra word or so per object of this type - which
may or may not be a big deal in your app. If the names inside the union
are globally unique, you can use macros to expand them out to their
fully-qualified versions.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #2

P: n/a
On 2004-09-14, Derrick Coetzee <dc****@moonflare.com> wrote:
This is called an anonymous union and it is a Microsoft extension. While
gcc supports MS extensions with the flag -fms-extensions, you'd do
better converting it to standard C. You can do this as you suggested. If
you want to avoid fixing up all references, you can simply dispose of
the union, costing an extra word or so per object of this type - which
may or may not be a big deal in your app. If the names inside the union
are globally unique, you can use macros to expand them out to their
fully-qualified versions.


Thank you Derrick, that cleared it right up.

--
Sean Dolan
Nov 14 '05 #3

P: n/a
Sean Dolan <se*****@bellsouth.net> writes:
typedef struct ntt {
int type;
union {
int i;
char* s;
};
}nt;

nt n;
n.i = 0;

I found a C example like this and could not get gcc 2.95.4 to compile it
(struct has no member named `i') until I declared an instance of the union:
union {
int i;
char* s;
}u;

and accessed like:
n.u.i = 0;

Is the first example valid? If so, where is the problem?


No, the first example is not valid. In the member declaration

int type;

"int" is the member type and "type" is the name of the member.

In the (attempted) member declaration

union { int i; char *s; };

"union { int i; char *s; }" is the member type, but there is no member
name. (Sub-unions and sub-structs don't flatten into the namespace of
the surrounding struct or union.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #4

P: n/a
one of simple/silly questions:
why use unions when we have classes? what makes union worth of using?
Nov 14 '05 #5

P: n/a
c453___ <mu**@nospam.o2.pl> writes:
one of simple/silly questions:
why use unions when we have classes? what makes union worth of using?


C doesn't have classes.
--
Ben Pfaff
email: bl*@cs.stanford.edu
web: http://benpfaff.org
Nov 14 '05 #6

P: n/a
> C doesn't have classes.
;) why use unions if we have structures?
Nov 14 '05 #7

P: n/a
c453___ <mu**@nospam.o2.pl> writes:
one of simple/silly questions:
why use unions when we have classes? what makes union worth of using?


Because we don't have classes. (This is comp.lang.c, not comp.lang.c++.)

And, of course, unions and classes are two different things. The
point of a union is that the members are all stored in the same
location (and reading a member other than the last one written invokes
undefined behavior in most cases).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #8

P: n/a
In article <opsebyi1kjekdo2r@pieszczoch>, c453___ <mu**@nospam.o2.pl>
wrote:
one of simple/silly questions:
why use unions when we have classes? what makes union worth of using?


Unions are very useful to organise employees to negotiate higher
salaries, better working conditions etc. Classes are more useful to
learn stuff, like C classes where someone teaches C and people like you
should listen carefully to learn.

There should be Usenet classes as well, where people could learn not to
post C++ questions to comp.lang.c.
Nov 14 '05 #9

P: n/a
"c453___" <mu**@nospam.o2.pl> wrote in message
news:opsebz20jcekdo2r@pieszczoch...
C doesn't have classes.

;) why use unions if we have structures?


All members of a union start at offset zero.

Each successive member of a struct starts at the next
available offset that is appropriate for the alignment
of that member and the preceding (if any) member.
Nov 14 '05 #10

P: n/a
On Tue, 14 Sep 2004 21:22:02 +0200, c453___ wrote:
C doesn't have classes.

;) why use unions if we have structures?


To save space, mainly. With a union, each member overlaps in memory, so
you can have one spot to store objects of different types. Of course,
accessing an object of a different type than was last stored (for example,
reading a double after you've just stored an int) is nonconforming, highly
unportable, and somewhat dangerous.

I have never actually used them in any of my programs, but I suppose I'm
not a typical programmer.
Nov 14 '05 #11

P: n/a
In <opsebz20jcekdo2r@pieszczoch> c453___ <mu**@nospam.o2.pl> writes:
;) why use unions if we have structures?


Because they are *completely* different things, idiot!

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #12

P: n/a
In <cc**************************@posting.google.com > so************@yahoo.com (Mark Piffer) writes:
union fsm_locals* align_to_union(char *ptr) // non-portable
{
uintptr_t a = (void*)ptr; // architecture & implementation dep.
This is incorrect C code on any architecture & implementation: you can't
assign a pointer to an integer without a cast to integer. A diagnostic is
*required*.
return (void*)((a+3u)&~3u); // choose any alignment appropriate for


This is semantically broken, if uintptr_t is wider than unsigned int.
The correct ANDing mask is computed like this: ~(uintptr_t)3.

I didn't bother reading the rest of the code: you have to master C
*before* attempting this kind of things.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #13

P: n/a
On 15 Sep 2004 18:24:06 GMT, Da*****@cern.ch (Dan Pop) wrote:
In <cc**************************@posting.google.com > so************@yahoo.com (Mark Piffer) writes:
union fsm_locals* align_to_union(char *ptr) // non-portable
{
uintptr_t a = (void*)ptr; // architecture & implementation dep.
This is incorrect C code on any architecture & implementation: you can't
assign a pointer to an integer without a cast to integer. A diagnostic is
*required*.

Is it for historic reasons that this kind of assignment isn't being
flagged as syntax error? As far as I understand it, no implicit
conversion acts here, it is just that the UB does the "expected" on
most architectures/compilers.
return (void*)((a+3u)&~3u); // choose any alignment appropriate for
This is semantically broken, if uintptr_t is wider than unsigned int.
The correct ANDing mask is computed like this: ~(uintptr_t)3.

Yuck. I really slept about this one.

I didn't bother reading the rest of the code: you have to master C
*before* attempting this kind of things.

Dan


If we fancy that I had written the above lines correctly, would you
care then? My questions are more about pointers into unions and their
alignment.

Mark

--
Mark Piffer
MCU and DSP programming & software design
Nov 14 '05 #14

P: n/a
ma*********@chello.at (Mark Piffer) writes:
On 15 Sep 2004 18:24:06 GMT, Da*****@cern.ch (Dan Pop) wrote:
In <cc**************************@posting.google.com > so************@yahoo.com (Mark Piffer) writes:
union fsm_locals* align_to_union(char *ptr) // non-portable
{
uintptr_t a = (void*)ptr; // architecture & implementation dep.


This is incorrect C code on any architecture & implementation: you can't
assign a pointer to an integer without a cast to integer. A diagnostic is
*required*.

Is it for historic reasons that this kind of assignment isn't being
flagged as syntax error?


Trying to make this a syntax error would make the grammar
unnecessarily complex and probably introduce further context
sensitivity. Why do you think it should be a syntax error?
--
Ben Pfaff
email: bl*@cs.stanford.edu
web: http://benpfaff.org
Nov 14 '05 #15

P: n/a
Ben Pfaff <bl*@cs.stanford.edu> writes:
ma*********@chello.at (Mark Piffer) writes:
On 15 Sep 2004 18:24:06 GMT, Da*****@cern.ch (Dan Pop) wrote:
In <cc**************************@posting.google.com >
so************@yahoo.com (Mark Piffer) writes:
union fsm_locals* align_to_union(char *ptr) // non-portable
{
uintptr_t a = (void*)ptr; // architecture & implementation dep.

This is incorrect C code on any architecture & implementation: you can't
assign a pointer to an integer without a cast to integer. A diagnostic is
*required*.

Is it for historic reasons that this kind of assignment isn't being
flagged as syntax error?


Trying to make this a syntax error would make the grammar
unnecessarily complex and probably introduce further context
sensitivity. Why do you think it should be a syntax error?


A lot of people incorrectly use the term "syntax error" to refer to
any error reported by a compiler. The first compiler I used (not a C
compiler) had a list of "syntax errors" that included things like
undeclared identifiers.

I think Mark was asking whether there are historical reasons a
compiler wouldn't issue a diagnostic message for an attempt to assign
a pointer value to an integer object. The answer, I think, is that
earlier (pre-ANSI) versions of C were less strict about type
compatibility.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #16

P: n/a
Keith Thompson <ks***@mib.org> wrote in message news:<ln************@nuthaus.mib.org>...
A lot of people incorrectly use the term "syntax error" to refer to
any error reported by a compiler. The first compiler I used (not a C
compiler) had a list of "syntax errors" that included things like
undeclared identifiers. It was a black day for me yesterday. After I had overcome the (valid!)
reprehension from Dan, I went on and produced more rubbish instead of
shutting up.

I think Mark was asking whether there are historical reasons a
compiler wouldn't issue a diagnostic message for an attempt to assign
a pointer value to an integer object. The answer, I think, is that
earlier (pre-ANSI) versions of C were less strict about type
compatibility.

I think I was asking why it is an error trying to assign a scalar type
to a aggregate type and vice versa, but not a pointer to/from an
arithmetic type. It is always incorrect C, so the hierarchy of
mutually assignable types could be restricted to the arithmetic types.

Mark
Nov 14 '05 #17

P: n/a
so************@yahoo.com (Mark Piffer) wrote in message news:<cc**************************@posting.google. com>...
Keith Thompson <ks***@mib.org> wrote in message news:<ln************@nuthaus.mib.org>...
I think I was asking why it is an error trying to assign a scalar type
to a aggregate type and vice versa, but not a pointer to/from an
arithmetic type. It is always incorrect C, so the hierarchy of ^^^^^^^^^^^^^^^ that should read _integral type_
mutually assignable types could be restricted to the arithmetic types.

Mark

Nov 14 '05 #18

P: n/a
In <cc**************************@posting.google.com > so************@yahoo.com (Mark Piffer) writes:
I think I was asking why it is an error trying to assign a scalar type
to a aggregate type and vice versa, but not a pointer to/from an
arithmetic type.
I don't get you. It *is* an error to assign a pointer to/from an
arithmetic type and the compiler *must* diagnose it. Only *explicit*
conversions (via casts) are allowed between integers and pointers.
It is always incorrect C, so the hierarchy of
mutually assignable types could be restricted to the arithmetic types.


It is already restricted to arithmetic types (with the notable exception
of the null pointer constant and void pointers to/from non-void
non-function pointers).

Are you sure you know what you're talking about?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #19

P: n/a
On 16 Sep 2004 15:42:01 GMT, Da*****@cern.ch (Dan Pop) wrote:
In <cc**************************@posting.google.com > so************@yahoo.com (Mark Piffer) writes:
I think I was asking why it is an error trying to assign a scalar type
to a aggregate type and vice versa, but not a pointer to/from an
arithmetic type.


I don't get you. It *is* an error to assign a pointer to/from an
arithmetic type and the compiler *must* diagnose it.

Mea culpa. I don't know the exact definition of diagnose/warning/error
and the behaviour that the translator must exhibit. I deduced from
gcc, which gives a warning for this kind of assignment but continues
to compile. So I suppose there is no distinction in the standard
between "fatal" and non-fatal semantic errors, is there?
It is always incorrect C, so the hierarchy of
mutually assignable types could be restricted to the arithmetic types.


It is already restricted to arithmetic types (with the notable exception
of the null pointer constant and void pointers to/from non-void
non-function pointers).

Are you sure you know what you're talking about?

Since I've been reading in the ISO standard, the quality of my coding
actually has deteriorated and my creative ideas are being overlayed by
the always present fear of the next unsuspected UB. Problem is, I
think I'll never reach the stadium of 100% correct code (== complete
standard in my brain, all chapters all the time). From reading c.l.c
I know that at least I'm not the only one wandering in darkness. ;)

Mark

--
Mark Piffer
MCU and DSP programming & software design
Nov 14 '05 #20

P: n/a
In article <news:41**************@news.chello.at>
Mark Piffer <ma*********@chello.at> wrote:
... I suppose there is no distinction in the standard
between "fatal" and non-fatal semantic errors, is there?


Yes. The standards (C89 and C99 both, and the ones in between if
you count them) just talk about "diagnostics". See also
<http://web.torek.net/torek/c/compiler.html>.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (4039.22'N, 11150.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #21

P: n/a
>>I don't get you. It *is* an error to assign a pointer to/from an
arithmetic type and the compiler *must* diagnose it.

Mea culpa. I don't know the exact definition of diagnose/warning/error
and the behaviour that the translator must exhibit. I deduced from
gcc, which gives a warning for this kind of assignment but continues
to compile. So I suppose there is no distinction in the standard
between "fatal" and non-fatal semantic errors, is there?


ANSI C talks about diagnostics and doesn't distinguish between
"fatal error", "error", "warning", and "go to bed without the Internet".

A fatal error is a diagnostic for which the compiler MUST obliterate all
traces of the source code.
A warning is a diagnostic for which the compiler need not obliterate all
traces of the source code.

ANSI C makes no distinction between these two, and does not require
a compiler to have any fatal errors (as defined above) at all. On
the other hand, nothing prohibits a compiler from allowing you to
try to run the result of compiling code consisting of encrypted
tokenized Visual Basic XORed with the King James version of the
Bible, either. (Certain OS/360 FORTRAN compilers would allow you to run
just about any old crap, after giving page upon page of compile-time
error messages, but if you actually tried to execute the statements
it couldn't deal with, it would, at run time, print an error message
and quit. On the other hand, if you never tried to execute those
statements, it might even work.)

ANSI C also permits diagnostics for just about any reason whatever,
for example:

foo.c line 30: warning, Al Gore is still President of the USA.
foo.c line 40: spelling error in comment
foo.c line 90: today is Tuesday
foo.c line 123: warning: suggest parentheses around assignment used as truth value
foo.c line 422: warning: inaccurate approximation of pi 3.7

and these are permitted regardless of how misleading or downright lies
they are (there IS NO line 90! and line 40 hasn't got a comment on it).

Gordon L. Burditt
Nov 14 '05 #22

P: n/a
Dan Pop <Da*****@cern.ch> wrote:
In <opsebz20jcekdo2r@pieszczoch> c453___ <mu**@nospam.o2.pl> writes:
;) why use unions if we have structures?


Because they are *completely* different things, idiot!


In addition to being gratuitously insulting, this doesn't
answer the question. Presumably the OP knows they are
different things, and the question could be paraphrased as
why do the different things exist, why are both needed;
i.e., what is the difference. And I think other respondants
have answered that.

Perhaps the OP is interested by the observation that, given
the rules of union access, most of the time a union could be
replaced by a struct with the same members, and the behaviour
would be the same (just some space would be wasted). In this
sense, the two are arguably rather far from being "completely
different": one is capable of behaving *almost* exactly like
the other one, in a sense being almost a superset of the other
(that is, struct is a near-superset of union, behaviourally).

The key difference here, the one scenario in which a union can
be (legally) accessed in a manner that a struct could not
"emulate", is when unsigned chars are involved. A union can be
used to examine the byte representation of larger objects, by
writing a value through one member and reading it through another.

If you are going to call someone an idiot in the course of
answering their question, you should be sure that your
answer is correct and actually addresses the question.

--Benjamin

Nov 14 '05 #23

P: n/a
In <1095412581.757304@yasure> Benjamin Ketcham <bk******@drizzle.com> writes:
Dan Pop <Da*****@cern.ch> wrote:
In <opsebz20jcekdo2r@pieszczoch> c453___ <mu**@nospam.o2.pl> writes:
;) why use unions if we have structures?
Because they are *completely* different things, idiot!


In addition to being gratuitously insulting, this doesn't
answer the question.


Because the question doesn't deserve a better answer *here*. The
answer is to be found in any decent C tutorial book, which is mandatory
reading *before* posting here.
Presumably the OP knows they are different things,
His question suggests the very opposite, so your "presumably" is fully
unwarranted. Someone understanding the difference between structures
and unions would not phrase his question like this.
and the question could be paraphrased as
why do the different things exist, why are both needed;
i.e., what is the difference.

^^^^^^^^^^^^^^^^^^^^^^
You contradicting yourself now: the OP knows they are different things
but he doesn't know the difference. If he doesn't know the difference,
then how does he know they are different things?

Again, this is C textbook stuff, completely inappropriate for the
newsgroup, unless the poster explicitly mentions that, *after* reading
the relevant chapter(s) from his book, he still does not understand the
difference and/or the need for using unions. Furthermore, any smiley in
such a request is misplaced.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #24

P: n/a
In <41**************@news.chello.at> ma*********@chello.at (Mark Piffer) writes:
Since I've been reading in the ISO standard, the quality of my coding
actually has deteriorated and my creative ideas are being overlayed by
the always present fear of the next unsuspected UB.


Then, ignore the ISO standard and use K&R2 as your reference. If your
code is blessed by K&R2, then it is highly unlikely that it invokes
undefined behaviour.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #25

P: n/a
Dan Pop <Da*****@cern.ch> wrote:
In <1095412581.757304@yasure> Benjamin Ketcham <bk******@drizzle.com> writes:
Dan Pop <Da*****@cern.ch> wrote:
In <opsebz20jcekdo2r@pieszczoch> c453___ <mu**@nospam.o2.pl> writes:

;) why use unions if we have structures?

Because they are *completely* different things, idiot!
In addition to being gratuitously insulting, this doesn't
answer the question.


Because the question doesn't deserve a better answer *here*. The
answer is to be found in any decent C tutorial book, which is mandatory
reading *before* posting here.


Whether it "deserves" a better answer, in your jaded opinion, the
fact is that the OP has been fortunate enough to *receive* a better
answer, thanks to the likes of Chris Torek et al; and not thanks
to you. IMO the question is perfectly appropriate for clc (once
rendered appropriate, by s/classes/structs/, that is).

If you have no answer to offer, only insults, then the rules of
Netiquette require that you keep your trap shut, Dan. You ought
to know that.
Presumably the OP knows they are different things,


His question suggests the very opposite, so your "presumably" is fully
unwarranted. Someone understanding the difference between structures
and unions would not phrase his question like this.
and the question could be paraphrased as
why do the different things exist, why are both needed;
i.e., what is the difference.

^^^^^^^^^^^^^^^^^^^^^^
You contradicting yourself now: the OP knows they are different things
but he doesn't know the difference. If he doesn't know the difference,
then how does he know they are different things?


Not at all. The OP may know that they are different, due to the
rabid insistence by pedants like yourself, but may not understand
why or how they are different.
Again, this is C textbook stuff, completely inappropriate for the
newsgroup, unless the poster explicitly mentions that, *after* reading
the relevant chapter(s) from his book, he still does not understand the
difference and/or the need for using unions.
Frankly, I haven't seen a C textbook that really addresses the
interesting fact that structs could be used in place of unions
without changing the behaviour, in all but an important minority
of cases. Merely understanding the semantics of unions and structs
may not be enough to realize this subtlety; thus, it seems quite
appropriate to discuss it here. Without calling anyone an "idiot".
Furthermore, any smiley in
such a request is misplaced.


Oh, so you'll criticize the use of smileys, but then you'll go ahead
and pepper your own output with "idiot" and other gratuitous insults.
Frankly, the quality of Usenet in general, and this newsgroup in
particular, would be much more positively impacted if you -- and I'd
say "you and all the others who engage in gratuitous insults", but
really it's pretty consistently just you, Dan; I hate to imagine what
the personal issues might be, behind your facade -- would keep your
insults to yourself, than if every smiley was automatically deleted.

Your style of "conversation" would be appropriate in, say, alt.flame.
Smileys are (often) annoying in a technical forum, but they don't really
matter. Gratuitous insults and personal attacks, OTOH, really do bring
an undesirable element into a technical forum, one which the "regulars"
ought to know better than to introduce even if an occasional rogue or
clueless one takes that low road.

Clean up your style, Dan, it is *quite* inappropriate for clc.
Just pretend that every question, clueless or not, was asked by
someone interviewing you for a job.

Nov 14 '05 #26

P: n/a
"Benjamin Ketcham" <bk******@drizzle.com> wrote in message
news:1095500075.630483@yasure...
Dan Pop <Da*****@cern.ch> wrote:
In <1095412581.757304@yasure> Benjamin Ketcham <bk******@drizzle.com> writes:
Dan Pop <Da*****@cern.ch> wrote:
In <opsebz20jcekdo2r@pieszczoch> c453___ <mu**@nospam.o2.pl> writes:
>;) why use unions if we have structures?

Because they are *completely* different things, idiot!

In addition to being gratuitously insulting, this doesn't
answer the question.

Well, it IS insulting. But it _does_ actually answer the question, which
AFAICT is, "Why have two things that are the same and call them by
different names?" As Dan points out, they are not the same thing, so the
question is silly.

To fix the unsociable part, if you just think "Friend" when Dan says
"Idiot", perhaps his posts would be more platable to you.
Whether it "deserves" a better answer, in your jaded opinion, the
fact is that the OP has been fortunate enough to *receive* a better
answer, thanks to the likes of Chris Torek et al; and not thanks
to you.
Well, newsgroups are not a friendly place to ask homework questions.
Caveat emptor, etc. It turns out that some answers posted to newsgroups
could be incorrect or hostile. I just thought I should break that news
to everyone.
If you have no answer to offer, only insults, then the rules of
Netiquette require that you keep your trap shut.
What does it say about hounding people that post brutaly honest posts? I
know there's a bit about posting just to correct spelling, so is there a
section on posting just to yell at someone who is mean? I wonder if it
would say something about anyone who reads a newsgroup is a grown-up and
if you don't like someone else's post that you keep your trap shut? If
not, maybe we could add that to Netiquette and prevent posts like yours
in the future (oh, and it would eliminate this one too!)
Frankly, I haven't seen a C textbook that really addresses the
interesting fact that structs could be used in place of unions
without changing the behaviour, in all but an important minority
of cases. Merely understanding the semantics of unions and structs
may not be enough to realize this subtlety; thus, it seems quite
appropriate to discuss it here. Without calling anyone an "idiot".
That statement makes me want to call you a "Friend" (see above), i.e. I
disagree. Somebody else will have to enumerate the ways this is wrong,
as I am speechless.
Clean up your style, Dan, it is *quite* inappropriate for clc.
Just pretend that every question, clueless or not, was asked by
someone interviewing you for a job.


I cannot argue against this wisdom, for Dan, myself, or anyone who
converses with humans or users

--
Mabden
Nov 14 '05 #27

P: n/a
"Mabden" <mabden@sbc_global.net> writes:
"Benjamin Ketcham" <bk******@drizzle.com> wrote in message
news:1095500075.630483@yasure...
Dan Pop <Da*****@cern.ch> wrote:
> In <1095412581.757304@yasure> Benjamin Ketcham <bk******@drizzle.com> writes: >
>>Dan Pop <Da*****@cern.ch> wrote:
>>> In <opsebz20jcekdo2r@pieszczoch> c453___ <mu**@nospam.o2.pl> writes: >>>
>>>>;) why use unions if we have structures?
>>>
>>> Because they are *completely* different things, idiot!
>>
>>In addition to being gratuitously insulting, this doesn't
>>answer the question.


Well, it IS insulting. But it _does_ actually answer the question, which
AFAICT is, "Why have two things that are the same and call them by
different names?" As Dan points out, they are not the same thing, so the
question is silly.


I believe you've misunderstood both the question and the answer.

No, they're not the same thing, but that's not what Dan said. He said
that "they are *completely* different things", which happens to be
untrue. Structures and unions differ in the keyword used to declare
them, in the layout of their members, and a few other things, but
they're very similar in some ways.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #28

P: n/a
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"Mabden" <mabden@sbc_global.net> writes:
"Benjamin Ketcham" <bk******@drizzle.com> wrote in message
news:1095500075.630483@yasure...
Dan Pop <Da*****@cern.ch> wrote:
> In <1095412581.757304@yasure> Benjamin Ketcham

<bk******@drizzle.com> writes:
>
>>Dan Pop <Da*****@cern.ch> wrote:
>>> In <opsebz20jcekdo2r@pieszczoch> c453___ <mu**@nospam.o2.pl>

writes:
>>>
>>>>;) why use unions if we have structures?
>>>
>>> Because they are *completely* different things, idiot!
>>
>>In addition to being gratuitously insulting, this doesn't
>>answer the question.


Well, it IS insulting. But it _does_ actually answer the question, which AFAICT is, "Why have two things that are the same and call them by
different names?" As Dan points out, they are not the same thing, so the question is silly.


I believe you've misunderstood both the question and the answer.

No, they're not the same thing, but that's not what Dan said. He said
that "they are *completely* different things", which happens to be
untrue. Structures and unions differ in the keyword used to declare
them, in the layout of their members, and a few other things, but
they're very similar in some ways.


Well, they are used for different purposes, and they perform different
tasks.
A union allows data to be stored as one type and read or manipulated as
different type(s). For instance, storing a 32bit value and using the
first byte as a char, the next 12bits as flags, 4bits as undefined, and
a final chksum.
That is not the purpose of a structure, which is a collection of
variables that are passed around together, often as an array. There is
no overlap of data, in fact there are usually "holes".

union example {
int32 input;
struct breakout {
char type;
unsigned int flags : 12;
: 4; // unused
char chksum;
} b;
} inpbuf;

One question: can unions be made into arrays?
Nov 14 '05 #29

P: n/a
Mabden wrote:
One question: can unions be made into arrays?


Arrays are agregates of objects with sequential addresses.
Unions are agregates of objects with the same address
(addresses which compare equal when suitably cast).
What do you mean?

--
pete
Nov 14 '05 #30

P: n/a
Mabden wrote:
.... snip ...
A union allows data to be stored as one type and read or
manipulated as different type(s). For instance, storing a 32bit
value and using the first byte as a char, the next 12bits as
flags, 4bits as undefined, and a final chksum.


This is not so, with the sole exception being when the read-out
type is an array of unsigned char. Anything else is, at best,
implementation defined.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #31

P: n/a
pete wrote:
Mabden wrote:
One question: can unions be made into arrays?


Arrays are agregates of objects with sequential addresses.
Unions are agregates of objects with the same address
(addresses which compare equal when suitably cast).
What do you mean?

Unions are not aggregates.

Brian Rodenborn
Nov 14 '05 #32

P: n/a
Default User wrote:

pete wrote:
Mabden wrote:
One question: can unions be made into arrays?


Arrays are agregates of objects with sequential addresses.
Unions are agregates of objects with the same address
(addresses which compare equal when suitably cast).
What do you mean?


Unions are not aggregates.


Thank you.

--
pete
Nov 14 '05 #33

P: n/a
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
No, they're not the same thing, but that's not what Dan said. He said
that "they are *completely* different things", which happens to be
untrue. Structures and unions differ in the keyword used to declare
them, in the layout of their members, and a few other things, but
they're very similar in some ways.


Please elaborate on the *semantic* similarities between unions and
structures. No matter how hard I try, I can see only differences...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #34

P: n/a
Da*****@cern.ch (Dan Pop) writes:
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
No, they're not the same thing, but that's not what Dan said. He said
that "they are *completely* different things", which happens to be
untrue. Structures and unions differ in the keyword used to declare
them, in the layout of their members, and a few other things, but
they're very similar in some ways.


Please elaborate on the *semantic* similarities between unions and
structures. No matter how hard I try, I can see only differences...


Try harder.

Unions and structures both have members. Each member has a type, an
offset, a size, etc. You can store and retrieve a value in a member.
For many (but not all) portable programs that use unions, you could
change the unions to structures and get the same behavior, except for
increased memory usage. And of course they're syntactically almost
identical.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #35

P: n/a
Keith Thompson wrote:

Da*****@cern.ch (Dan Pop) writes:
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
No, they're not the same thing, but that's not what Dan said. He said
that "they are *completely* different things", which happens to be
untrue. Structures and unions differ in the keyword used to declare
them, in the layout of their members, and a few other things, but
they're very similar in some ways.


Please elaborate on the *semantic* similarities between unions and
structures. No matter how hard I try, I can see only differences...


Try harder.

Unions and structures both have members. Each member has a type, an
offset, a size, etc. You can store and retrieve a value in a member.
For many (but not all) portable programs that use unions, you could
change the unions to structures and get the same behavior, except for
increased memory usage.


In any case where you could replace a union with a structure
and get the same behavior, except for increased memory usage,
wouldn't the most likely reason for the union in the first place,
be to save memory?

--
pete
Nov 14 '05 #36

P: n/a
pete <pf*****@mindspring.com> writes:
Keith Thompson wrote:
Da*****@cern.ch (Dan Pop) writes:
> In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
>>No, they're not the same thing, but that's not what Dan said. He said
>>that "they are *completely* different things", which happens to be
>>untrue. Structures and unions differ in the keyword used to declare
>>them, in the layout of their members, and a few other things, but
>>they're very similar in some ways.
>
> Please elaborate on the *semantic* similarities between unions and
> structures. No matter how hard I try, I can see only differences...


Try harder.

Unions and structures both have members. Each member has a type, an
offset, a size, etc. You can store and retrieve a value in a member.
For many (but not all) portable programs that use unions, you could
change the unions to structures and get the same behavior, except for
increased memory usage.


In any case where you could replace a union with a structure
and get the same behavior, except for increased memory usage,
wouldn't the most likely reason for the union in the first place,
be to save memory?


Yes.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #37

P: n/a
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
pete <pf*****@mindspring.com> writes:
Keith Thompson wrote:
Da*****@cern.ch (Dan Pop) writes:
> In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes: >>No, they're not the same thing, but that's not what Dan said. He said >>that "they are *completely* different things", which happens to be >>untrue. Structures and unions differ in the keyword used to declare >>them, in the layout of their members, and a few other things, but
>>they're very similar in some ways.
>
> Please elaborate on the *semantic* similarities between unions and > structures. No matter how hard I try, I can see only differences...
Try harder.

Unions and structures both have members. Each member has a type, an offset, a size, etc. You can store and retrieve a value in a member. For many (but not all) portable programs that use unions, you could
change the unions to structures and get the same behavior, except for increased memory usage.


In any case where you could replace a union with a structure
and get the same behavior, except for increased memory usage,
wouldn't the most likely reason for the union in the first place,
be to save memory?


Yes.


No. Duh. I have never seen a union used to save memory.

The main reason to use unions is to take in chunk of data in binary form
and break it down into meaningful data. Things like packets that come in
as X number of bits, and pulling out the real data as flags and bytes.
We do this all the time when communicating with the mainframe.

Structs and unions have a similar definition, so the Standards Whores
think they are the same, but in fact if they were that similar you
could, for instance make a union array. That doesn't make sense, so that
is one difference unions and structures have.

You could just as well say that functions and arrays are the same thing
because they both have curly braces to begin and end them.

--
Mabden
Nov 14 '05 #38

P: n/a
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
Da*****@cern.ch (Dan Pop) writes:
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
No, they're not the same thing, but that's not what Dan said. He said
that "they are *completely* different things", which happens to be
untrue. Structures and unions differ in the keyword used to declare
them, in the layout of their members, and a few other things, but
they're very similar in some ways.
Please elaborate on the *semantic* similarities between unions and
structures. No matter how hard I try, I can see only differences...


Try harder.

Unions and structures both have members. Each member has a type, an
offset, a size, etc.


With the *significant* difference that all offsets in a union are zero.
Which is what makes both things *completely* different semantically: one
is grouping a number of related entities together, the other is
overlapping them.
You can store and retrieve a value in a member.
Not true for unions:

struct foo s;
union bar u;

s.a = 1;
s.b = 2;

u.a = 1;
u.b = 2;

You can now retrieve the value stored in the member s.a, but not the
value stored in the member u.a. The degenerate case when you use only
one member does NOT matter, because it does not warrant the usage of a
structure or union in the first place.
For many (but not all) portable programs that use unions, you could
change the unions to structures and get the same behavior, except for
increased memory usage.
Since this is not valid for *all* portable programs (one of the most
common uses of unions in portable programs relies on all member
offsets being zero), it doesn't count as a valid argument. It is like
saying: for many (but not all) portable programs that use integer
arithmetic, you could change the integer types by floating point types
and get the same behaviour, except for increased memory usage.
And of course they're syntactically almost identical.


Which means exactly zilch. if and while are also syntactically almost
identical, yet they are still completely different things.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #39

P: n/a
"Mabden" <mabden@sbc_global.net> wrote:
Structs and unions have a similar definition, so the Standards Whores
think they are the same, but in fact if they were that similar you
could, for instance make a union array.


Well, then here's your lesson for today, and maybe it'll teach you not
to use words like "whores" again in a hurry: you _can_ create union
arrays. I could even think of a reasonable application.

Richard
Nov 14 '05 #40

P: n/a
Dan Pop wrote:
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
Da*****@cern.ch (Dan Pop) writes:
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org>
writes:
No, they're not the same thing, but that's not what Dan said. He said
that "they are *completely* different things", which happens to be
untrue. Structures and unions differ in the keyword used to declare
them, in the layout of their members, and a few other things, but
they're very similar in some ways.

Please elaborate on the *semantic* similarities between unions and
structures. No matter how hard I try, I can see only differences...


Try harder.

Unions and structures both have members. Each member has a type, an
offset, a size, etc.


With the *significant* difference that all offsets in a union are zero.
Which is what makes both things *completely* different semantically: one
is grouping a number of related entities together, the other is
overlapping them.
You can store and retrieve a value in a member.


Not true for unions:

struct foo s;
union bar u;

s.a = 1;
s.b = 2;

u.a = 1;
u.b = 2;


True for unions:

union bar u;
u.a = 1;
u.a += 1;

The difference is just that writing into one member makes the other
member's values undefined, which in turn is why overlapping them
makes sense.
And of course they're syntactically almost identical.


Which means exactly zilch. if and while are also syntactically almost
identical, yet they are still completely different things.


You must have some awsomely picky notion of sameness, then, since
both if [1] and while are semantically very similar things - they
have an expression component, which they evaluate in the same way
and which guards the statement component, which they also evaluate
the same way; the differences are that the while repeats itself
and the if doesn't, and the while rebinds the meaning of break
and continue, and the if doesn't.

You'd have been better off picking switch vs if, since the switch-
expression isn't evaluated as a boolean, and its component compound
statement isn't evaluated in the same way as other compound statements.

[1] if-without-else, otherwise they wouldn't be "syntactically almost
identical".

--
Chris "electric hedgehog" Dollin
C FAQs at: http://www.faqs.org/faqs/by-newsgrou...mp.lang.c.html
C welcome: http://www.angelfire.com/ms3/bchambl...me_to_clc.html
Nov 14 '05 #41

P: n/a
Mabden wrote:
.... snip ...
No. Duh. I have never seen a union used to save memory.
You obviously haven't done much system programming. This is the
primary use for them.

The main reason to use unions is to take in chunk of data in
binary form and break it down into meaningful data. Things like
packets that come in as X number of bits, and pulling out the
real data as flags and bytes. We do this all the time when
communicating with the mainframe.
This is probably (depending on types) non-portable coding, and
should be concentrated in system-dependant files. Sooner or later
that dog will byte.

Structs and unions have a similar definition, so the Standards
Whores think they are the same, but in fact if they were that
similar you could, for instance make a union array. That doesn't
make sense, so that is one difference unions and structures have.


Except it does make sense, and arrays of unions are implemented
all the time. Your inexperience is showing again.

--
"It is not a question of staying the course, but of changing
the course" - John Kerry, 2004-09-20
"Ask any boat owner the eventual result of continuing the
present course indefinitely" - C.B. Falconer, 2004-09-20
Nov 14 '05 #42

P: n/a
In <ci**********@news.unix-apps.rit.sc2.udc.hpl.hp.com> Chris Dollin <ke**@hpl.hp.com> writes:
Dan Pop wrote:
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
Da*****@cern.ch (Dan Pop) writes:
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org>
writes:
>No, they're not the same thing, but that's not what Dan said. He said
>that "they are *completely* different things", which happens to be
>untrue. Structures and unions differ in the keyword used to declare
>them, in the layout of their members, and a few other things, but
>they're very similar in some ways.

Please elaborate on the *semantic* similarities between unions and
structures. No matter how hard I try, I can see only differences...

Try harder.

Unions and structures both have members. Each member has a type, an
offset, a size, etc.


With the *significant* difference that all offsets in a union are zero.
Which is what makes both things *completely* different semantically: one
is grouping a number of related entities together, the other is
overlapping them.
You can store and retrieve a value in a member.


Not true for unions:

struct foo s;
union bar u;

s.a = 1;
s.b = 2;

u.a = 1;
u.b = 2;


True for unions:

union bar u;
u.a = 1;
u.a += 1;

The difference is just that writing into one member makes the other
member's values undefined, which in turn is why overlapping them
makes sense.


Which is precisely what makes unions and structures completely different
things, despite any *superficial* similarities.
And of course they're syntactically almost identical.


Which means exactly zilch. if and while are also syntactically almost
identical, yet they are still completely different things.


You must have some awsomely picky notion of sameness, then, since
both if [1] and while are semantically very similar things -


You must have some awsomely lax notion of sameness, if the if and while
statements look semantically very similar to you. To me, the only
statements semantically close to while are do and for.

Then again, a wheel mouse and a wheelbarrow might be semantically very
similar things to you...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #43

P: n/a
"Mabden" <mabden@sbc_global.net> writes:
No. Duh. I have never seen a union used to save memory.


Here's an example:

/* Node in a parse tree for a simple expression grammar. */
struct node {
enum { PLUS, MINUS, TIMES, DIV, VAR, NUM } type;
union {
struct node *operands[2]; /* PLUS, MINUS, TIMES, DIV: operands. */
const char *var_name; /* VAR: variable name. */
double num; /* NUM: numerical value. */
} u;
};

If you change "union" to "struct", it works just as well, but you
waste memory.
--
Ben Pfaff
email: bl*@cs.stanford.edu
web: http://benpfaff.org
Nov 14 '05 #44

P: n/a

In article <Zh******************@newssvr21.news.prodigy.com >, "Mabden" <mabden@sbc_global.net> writes:

No. Duh. I have never seen a union used to save memory.
Duh indeed. What makes you think that your personal experience is
definitive?

*I* have certainly seen unions used to save memory; I may have used
them that way myself, though it's a matter of interpretation. (If I
use a union as a container for various types of data, only one of
which will be stored in it, for reasons of elegance and efficiency
rather than to "save memory" per se, does that count?)

Note that even on systems with ample memory, a union may often win
over a structure with redundant members because of the limited size
of cache lines, among other things.
The main reason to use unions is to take in chunk of data in binary form
and break it down into meaningful data. Things like packets that come in
as X number of bits, and pulling out the real data as flags and bytes.
The "main reason", eh? You've surveyed a representative sample of
C programmers to determine this?
We do this all the time when communicating with the mainframe.
Well hooray for you. Those of us who have to write *portable* C
comms code don't like to make assumptions about how implementations
will lay things out in memory, so we don't use unions for type
punning; we marshall and unmarshall packets manually, using unsigned
char, in the manner actually supported by the language.
Structs and unions have a similar definition, so the Standards Whores
think they are the same, but in fact if they were that similar you
could, for instance make a union array. That doesn't make sense, so that
is one difference unions and structures have.
What are you talking about? You can make arrays of unions, and you
can put arrays inside unions. What's a "union array"?
You could just as well say that functions and arrays are the same thing
because they both have curly braces to begin and end them.


This is as bogus an analogy as I have seen here in some time. unions
and structs are obviously more similar than functions and arrays,
since the former pair are both data structures; and arrays don't
"begin and end" with "curly braces" (though array initializers do).

--
Michael Wojcik mi************@microfocus.com

When [Columbus] landed on America it was more like an evasion than a
discovery. -- Matt Walsh
Nov 14 '05 #45

P: n/a
"Mabden" <mabden@sbc_global.net> writes:
[...]
No. Duh. I have never seen a union used to save memory.

The main reason to use unions is to take in chunk of data in binary form
and break it down into meaningful data. Things like packets that come in
as X number of bits, and pulling out the real data as flags and bytes.
We do this all the time when communicating with the mainframe.

Structs and unions have a similar definition, so the Standards Whores
think they are the same, but in fact if they were that similar you
could, for instance make a union array. That doesn't make sense, so that
is one difference unions and structures have.

You could just as well say that functions and arrays are the same thing
because they both have curly braces to begin and end them.


Apart from your other errors, nobody has claimed that structs and
unions are the same. Obviously they're quite different in many ways.

This whole argument is about a claim that structs and unions are
"completely different". They are neither identical nor completely
different; they're similar in some ways, different in others.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #46

P: n/a
"Mabden" <mabden@sbc_global.net> wrote:
Da*****@cern.ch (Dan Pop) writes:
> Please elaborate on the *semantic* similarities between
> unions and structures. No matter how hard I try, I can
> see only differences...
The main reason to use unions is to take in chunk of data in binary form
and break it down into meaningful data. Things like packets that come in
as X number of bits, and pulling out the real data as flags and bytes.
Undefined behaviour.
We do this all the time when communicating with the mainframe.
What happens when you change to a new compiler and the code
stops working?
Structs and unions have a similar definition, so the Standards Whores
think they are the same, but in fact if they were that similar you
could, for instance make a union array. That doesn't make sense, so that
is one difference unions and structures have.


What doesn't make sense about an array of unions?
Nov 14 '05 #47

P: n/a
ol*****@inspire.net.nz (Old Wolf) writes:
"Mabden" <mabden@sbc_global.net> wrote:
> Da*****@cern.ch (Dan Pop) writes:
>> Please elaborate on the *semantic* similarities between
>> unions and structures. No matter how hard I try, I can
>> see only differences...

The main reason to use unions is to take in chunk of data in binary form
and break it down into meaningful data. Things like packets that come in
as X number of bits, and pulling out the real data as flags and bytes.


Undefined behaviour.
We do this all the time when communicating with the mainframe.


What happens when you change to a new compiler and the code
stops working?

[...]

If the code stops working, you change back to the old compiler.

Undefined behavior doesn't *guarantee* nasal demons, and non-portable
code can be acceptable if you understand that it's non-portable and
you're sufficiently careful about it.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #48

P: n/a
"CBFalconer" <cb********@yahoo.com> wrote in message
news:41***************@yahoo.com...
Mabden wrote:

... snip ...

No. Duh. I have never seen a union used to save memory.


You obviously haven't done much system programming. This is the
primary use for them.


Well, I have only used them to take raw packets and break them up into
fields. Usually IPX or whatnot. As you point out, very non-portable
stuff.
The main reason to use unions is to take in chunk of data in
binary form and break it down into meaningful data. Things like
packets that come in as X number of bits, and pulling out the
real data as flags and bytes. We do this all the time when
communicating with the mainframe.


This is probably (depending on types) non-portable coding, and
should be concentrated in system-dependant files. Sooner or later
that dog will byte.


Of course.
Structs and unions have a similar definition, so the Standards
Whores think they are the same, but in fact if they were that
similar you could, for instance make a union array. That doesn't
make sense, so that is one difference unions and structures have.


Except it does make sense, and arrays of unions are implemented
all the time. Your inexperience is showing again.


I didn't mean an array of unions. I said a union can't be used as an
array. I don't think you can say:

union interface {
int input;
int ouput;
} u [50];

can you?

--
Mabden
Nov 14 '05 #49

P: n/a
"Mabden" <mabden@sbc_global.net> writes:
I didn't mean an array of unions. I said a union can't be used as an
array. I don't think you can say:

union interface {
int input;
int ouput;
} u [50];

can you?


That *is* an array of unions and yes you can do that.
--
"Large amounts of money tend to quench any scruples I might be having."
-- Stephan Wilms
Nov 14 '05 #50

73 Replies

This discussion thread is closed

Replies have been disabled for this discussion.