union access

M

Mark Piffer

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 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
 
G

Gordon Burditt

I don't get you. It *is* an error to assign a pointer to/from an
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
 
B

Benjamin Ketcham

Dan Pop said:
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
 
D

Dan Pop

In said:
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
 
D

Dan Pop

In said:
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
 
B

Benjamin Ketcham

Dan Pop said:
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.
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.

^^^^^^^^^^^^^^^^^^^^^^
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.
 
M

Mabden

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
 
K

Keith Thompson

Mabden said:
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.
 
M

Mabden

Keith Thompson said:
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?
 
P

pete

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?
 
C

CBFalconer

Mabden said:
.... 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.
 
D

Default User

pete said:
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
 
D

Dan Pop

In said:
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
 
K

Keith Thompson

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.
 
P

pete

Keith said:
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?
 
K

Keith Thompson

pete said:
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.
 
M

Mabden

Keith Thompson said:

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.
 
D

Dan Pop

In said:
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
 

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

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top