Structures vs. Unions 
Author Message
 Structures vs. Unions

    Can someone please tell me what the difference is between a structure
and a union.  I have read 2 different books and a tutorial and none of them
go into very much detail about what the differences are.  When would you
choose to use a union over a struct or vice versa?  Thanks!
            -Ike Gingerich


Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions
A union allows you to share the same memory location for one or more
variables so you can reference and act upon it as different data types or
formats.  For instance, if you needed to swap the byte order of an int, you
can declare a union on the int so that it also looks like an array of
characters.  Then you can swap the bytes quite easily.  You can also use a
union to define the fields in a record.  Lets say you have two types of
records to read in, and you want to store them in the same memory location,
but need to break them apart into different record layouts.  You declare the
buffer, and then two unions to the buffer with the different record layouts.
Then you reference the correct union based upon which record type you
brought in.

--
****************************************
Richard Armstrong
State Of The Art Consulting, Inc.
http://www.stateoart.com
****************************************

Quote:

>     Can someone please tell me what the difference is between a structure
> and a union.  I have read 2 different books and a tutorial and none of
them
> go into very much detail about what the differences are.  When would you
> choose to use a union over a struct or vice versa?  Thanks!
>             -Ike Gingerich



Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions

Quote:

> A union allows you to share the same memory location for one or more
> variables so you can reference and act upon it as different data types or
> formats.  For instance, if you needed to swap the byte order of an int, you
> can declare a union on the int so that it also looks like an array of
> characters.  Then you can swap the bytes quite easily.  You can also use a

RED ALERT: Undefined Behavior

Quote:
> union to define the fields in a record.  Lets say you have two types of
> records to read in, and you want to store them in the same memory location,
> but need to break them apart into different record layouts.  You declare the
> buffer, and then two unions to the buffer with the different record layouts.
> Then you reference the correct union based upon which record type you
> brought in.

> --
> ****************************************
> Richard Armstrong
> State Of The Art Consulting, Inc.
> http://www.stateoart.com
> ****************************************

> >     Can someone please tell me what the difference is between a structure
> > and a union.  I have read 2 different books and a tutorial and none of
> them
> > go into very much detail about what the differences are.  When would you
> > choose to use a union over a struct or vice versa?  Thanks!
> >             -Ike Gingerich

--
--------------------------------------

CCG               http://www.ccg.uc.pt
--------------------------------------



Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions

Quote:

>     Can someone please tell me what the difference is between a structure
> and a union.  I have read 2 different books and a tutorial and none of them
> go into very much detail about what the differences are.  When would you
> choose to use a union over a struct or vice versa?  Thanks!
>             -Ike Gingerich

First of all, I would find better tutorials and books!  This question is
quite basic and any C language reference should explain it clearly.

Now to your question.  The members of a struct do not overlap in memory.
Assigning to one member of a struct has no effect on any other.

The members of a union overlap in memory.  Assigning to one member of a
union invalidates all the other members.

Structs are much more commonly used than unions.  Unions are mostly for
saving memory when it's tight or for system-specific tricks.  IMO, a
beginner should ignore them.

--
James M. Stern                Northrop Grumman Corp.  Hawthorne, CA
Opinions expressed above are not necessarily my employer's.



Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions

Quote:

>     Can someone please tell me what the difference is between a structure
> and a union.  I have read 2 different books and a tutorial and none of them
> go into very much detail about what the differences are.  When would you
> choose to use a union over a struct or vice versa?  Thanks!
>             -Ike Gingerich

If you want to group some variables together because they are somehow
related you use a structure. An example would be a structure for
personal data:

struct persdata {
        char lastname[20] ;
        char firstname[20] ;
        char adress[40] ;
        char city [20] ;
        etc...

Quote:
} ;

Instead of using this structure to save a person's personal data you
could also use single variables. One char-array for the last name, one
for the first name, etc., but grouping this data together in a structure
makes your program more readable and makes it easier to pass that data
to functions.

If it is possible that a variable can contain values of different data
types you use a union. In a union the components are stored at the same
location in memory, whereas in a structure they are stored sequentially.
An example to for using a structure would be if your program asks the
user to input his age and you want to give the user the choice between
giving his age as number ("12") or as text ("twelve") you could use an
union like this:

union age {
        int age_int ;
        char age_char[20] ;

Quote:
} ;

If the user enters "12" age_int contains 12 and you *should* access the
data in the union only using age.age_int. If user enters "twelve"
age_char contains "twelve" and - again - you should access the data in
the union only usinge age.age_char. When reading data from a union you
have to use the same component (of the union) that you used when you
wrote that data into the union.

I know the union-example is pretty stupid, but I hope you get the idea.
Maybe someone can come up with a better example...

Stefan



Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions
: A union allows you to share the same memory location for one or more
: variables so you can reference and act upon it as different data types or
: formats.

A key concept here is the mutual exclusion in time of these data types.
IOW, if you need space for an int and a float, but never at the same
time, putting them in a union can save you some space.

: For instance, if you needed to swap the byte order of an int, you
: can declare a union on the int so that it also looks like an array of
: characters.  Then you can swap the bytes quite easily.

This is an *abuse* of the union construct.  Retrieving using a
different type than the element was stored results in implementation-
defined behavior.  Unions are not meant to help you skirt around
the type system.  Unfortunately, this seems to be a common
misconception, because everytime somebody asks about unions, this
solution appears as an answer.  :(  This results in *unnecessarily*
non-portable code.

: You can also use a
: union to define the fields in a record.  Lets say you have two types of
: records to read in, and you want to store them in the same memory location,
: but need to break them apart into different record layouts.  You declare the
: buffer, and then two unions to the buffer with the different record layouts.
: Then you reference the correct union based upon which record type you
: brought in.

This is a much better example.  Note that once you've decided which
type the union is, you only access it as that type.  Here are some
other examples:

1.  Symbol table - a compiler or interpreter may need to maintain
    the identifier of a variable, and perhaps its value.  The value
    may be one of several types, but only one type at a time.  So,
    instead of declaring:

    int int_value;
    double double_value;
    float float_value;

    and so on, they can be declared in a union to save space.

2.  Spreadsheet - each cell may hold a formula, or a text label, or
    a constant, but only one of them at a time.

To answer the original question, unions offer space savings over
structs by reusing the storage of an element that the programmer
is sure would not be needed at that time.  You can always start
with structs, and identify those elements that are mutually-
exclusive in time later.



Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions
: A union allows you to share the same memory location for one or more
: variables so you can reference and act upon it as different data types or
: formats.  For instance, if you needed to swap the byte order of an int, you
: can declare a union on the int so that it also looks like an array of
: characters.  Then you can swap the bytes quite easily.  You can also use a
: union to define the fields in a record.  Lets say you have two types of
: records to read in, and you want to store them in the same memory location,
: but need to break them apart into different record layouts.  You declare the
: buffer, and then two unions to the buffer with the different record layouts.
: Then you reference the correct union based upon which record type you
: brought in.

The second instance is ok, but note that the first instance
gives undefined behaviour.  You're allowed to extract from a union
only what you put into it.  Still, it's pretty convenient if it works.

Will



Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions

Quote:
> : For instance, if you needed to swap the byte order of an int, you
> : can declare a union on the int so that it also looks like an array of
> : characters.  Then you can swap the bytes quite easily.

> This is an *abuse* of the union construct.  Retrieving using a
> different type than the element was stored results in implementation-
> defined behavior.  Unions are not meant to help you skirt around
> the type system.  Unfortunately, this seems to be a common
> misconception, because everytime somebody asks about unions, this
> solution appears as an answer.  :(  This results in *unnecessarily*
> non-portable code.

In the non-portable world we live in, this is often the way to read binary
files from one platform on another (a PC generated binary file read on a
Unix box for example, without having to modify the binary file -- maybe on a
shared mount between Unix and PC's).   What if you need to create a binary
file on a Unix box that is stored for PC's to read?   I would not call it an
abuse.  It is a fact of life.  Besides, how do you think sophisticated
dynamic client-server middleware is written?  Not everything can be known at
compile time and thrown into an RPC.  Perhaps the reason so many answer the
question with this response so often has to do with the fact that it is
common?

--
****************************************
Richard Armstrong
State Of The Art Consulting, Inc.
http://www.stateoart.com
****************************************

Quote:

> : A union allows you to share the same memory location for one or more
> : variables so you can reference and act upon it as different data types
or
> : formats.

> A key concept here is the mutual exclusion in time of these data types.
> IOW, if you need space for an int and a float, but never at the same
> time, putting them in a union can save you some space.

> : For instance, if you needed to swap the byte order of an int, you
> : can declare a union on the int so that it also looks like an array of
> : characters.  Then you can swap the bytes quite easily.

> This is an *abuse* of the union construct.  Retrieving using a
> different type than the element was stored results in implementation-
> defined behavior.  Unions are not meant to help you skirt around
> the type system.  Unfortunately, this seems to be a common
> misconception, because everytime somebody asks about unions, this
> solution appears as an answer.  :(  This results in *unnecessarily*
> non-portable code.

> : You can also use a
> : union to define the fields in a record.  Lets say you have two types of
> : records to read in, and you want to store them in the same memory
location,
> : but need to break them apart into different record layouts.  You declare
the
> : buffer, and then two unions to the buffer with the different record
layouts.
> : Then you reference the correct union based upon which record type you
> : brought in.

> This is a much better example.  Note that once you've decided which
> type the union is, you only access it as that type.  Here are some
> other examples:

> 1.  Symbol table - a compiler or interpreter may need to maintain
>     the identifier of a variable, and perhaps its value.  The value
>     may be one of several types, but only one type at a time.  So,
>     instead of declaring:

>     int int_value;
>     double double_value;
>     float float_value;

>     and so on, they can be declared in a union to save space.

> 2.  Spreadsheet - each cell may hold a formula, or a text label, or
>     a constant, but only one of them at a time.

> To answer the original question, unions offer space savings over
> structs by reusing the storage of an element that the programmer
> is sure would not be needed at that time.  You can always start
> with structs, and identify those elements that are mutually-
> exclusive in time later.



Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions
Lower the shields.. Cancel Red Alert.

It is not undefined behavior if it is a defined behavior in a
specification... such as writing a binary file in a format that another
machine can read...  There is no reason to swap the bytes of an int other
than to convert the int into another machine's architecture, or convert it
so you can see it, since the int came from another machine architecture.  A
union is an obvious choice for this problem, and the most commonly used
method.  It is not evil.

--
****************************************
Richard Armstrong
State Of The Art Consulting, Inc.
http://www.stateoart.com
****************************************

Quote:

> > A union allows you to share the same memory location for one or more
> > variables so you can reference and act upon it as different data types
or
> > formats.  For instance, if you needed to swap the byte order of an int,
you
> > can declare a union on the int so that it also looks like an array of
> > characters.  Then you can swap the bytes quite easily.  You can also use
a

> RED ALERT: Undefined Behavior

> > union to define the fields in a record.  Lets say you have two types of
> > records to read in, and you want to store them in the same memory
location,
> > but need to break them apart into different record layouts.  You declare
the
> > buffer, and then two unions to the buffer with the different record
layouts.
> > Then you reference the correct union based upon which record type you
> > brought in.

> > --
> > ****************************************
> > Richard Armstrong
> > State Of The Art Consulting, Inc.
> > http://www.stateoart.com
> > ****************************************

> > >     Can someone please tell me what the difference is between a
structure
> > > and a union.  I have read 2 different books and a tutorial and none of
> > them
> > > go into very much detail about what the differences are.  When would
you
> > > choose to use a union over a struct or vice versa?  Thanks!
> > >             -Ike Gingerich

> --
> --------------------------------------

> CCG               http://www.ccg.uc.pt
> --------------------------------------



Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions


Quote:
>Lower the shields.. Cancel Red Alert.

>It is not undefined behavior if it is a defined behavior in a
>specification...

A program specification can't change undefined behaviour, undefined behaviour
means that the behaviour of the entire program from that point on is
entirely unpredictable.

Quote:
>such as writing a binary file in a format that another
>machine can read... There is no reason to swap the bytes of an int other
>than to convert the int into another machine's architecture, or convert it
>so you can see it, since the int came from another machine architecture.

You're missing the point. If you invoke undefined behaviour there are no
guarantees whatsoever that this will be the result. The program may simply
crash at that point or some arbitrary point later on.

Quote:
> A union is an obvious choice for this problem, and the most commonly used
>method.  It is not evil.

unions are not generally appropriate for things like byte swapping.
Use of pointers and pointer casts is generally much more appropriate
for this. It may well be commonly used, but so it seems is gets().

--
-----------------------------------------


-----------------------------------------



Mon, 24 Sep 2001 03:00:00 GMT  
 Structures vs. Unions
[...]
: I provided an example that everyone can understand and
: sympathize with.  An example that every C programmer will encounter before
: retirement.  An example that is taught in most systems programming courses.
: Swapping bytes in memory is not evil, and not a single programmer, hacker,
: puppy, or kitty cat has not made it through the Pearly Gates because they
: swapped the bytes of an int.
[...]

The problem isn't how evil this hack is, rather how simple the alternative
is.  To swap the bytes of a 16-bit integer, simply:

  after = ((before >> 8) & 0xFF) | ((before << 8) & 0xFF00);

The above is portable and simple.  Given that, why would you propose
something that is not portable?

I had hoped that specifically mentioning that this is a common
mistake would prevent a hostile response, but it appears I failed
anyway.  Note that you didn't (and still haven't, I think) told us
if you are doing this deliberately or unknowingly.  It is important
to teach beginners the right thing, and failing that, at least
point out that it's a non-portable trick.

Here's some proof:

p148 K&R2:

  "the results are implementation-defined if something is stored
   as one type and extracted as another."

J.3.9 C9X ("Implementation-defined behavior"):

  "The behavior when a member of a union object is accessed using
   a member of a different type."

Now, the C Standard doesn't differentiate between "evil", "not evil",
or "really evil", and neither should a responsible programmer and
teacher.  It is unwise, period, to rely on implementation-defined
behavior unless you *have* to.  In order to convert byte order in
an integer, you don't.

IMHO, once you start justifying your programming mistakes with
"it's not *that* evil", you've gone down the wrong path.  What's
so hard about just doing the right thing, even though you don't
consider the alternative too wrong?  Isn't that simply better
programming?



Mon, 24 Sep 2001 03:00:00 GMT  
 
 [ 25 post ]  Go to page: [1] [2]

 Relevant Pages 

1. Question regarding unions and structures

2. fread w/ Union structures

3. Initialising Union members of Structures

4. Bit-fields, unions and structures...

5. structure, union & enumeration tags

6. help: unnamed unions within structures

7. Union within structures

8. Alignment of data in a Structure/Union

9. structure union mess

10. Problems with structure+union

11. Structures & Unions

12. Structure and union.

 

 
Powered by phpBB® Forum Software