struct vs. union

This is a discussion on struct vs. union within the C Programming forums, part of the General Programming Boards category; When I was learning about structs and unions I understood the differences just fine...except for one part. My book never ...

  1. #1
    Registered User Draco's Avatar
    Join Date
    Apr 2002
    Posts
    463

    struct vs. union

    When I was learning about structs and unions I understood the differences just fine...except for one part. My book never says if you need to do anything special when using unions to make sure you're only using one of the variables at once. I can only think of a few looping situations, or linked lists where one would have to even worry about it.

  2. #2
    Registered User
    Join Date
    Aug 2003
    Posts
    51
    sometimes you would use unions using more than 1 type at a time. Other times not.

    Things like extracting the sign, mantissa and exponent from a float. Depends on how the programmer wants to use a union.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >My book never says if you need to do anything special when using unions to make sure you're only using one of the variables at once.
    The most common way of doing this is something like so:
    Code:
    struct fooby {
        enum { INT_TYPE, DBL_TYPE, CHAR_TYPE } type;
        union {
            double d;
            int i;
            char c;
        };
    };
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting from C to C++
    By Taka in forum C++ Programming
    Replies: 5
    Last Post: 04-08-2009, 03:16 AM
  2. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  3. Looking for a way to store listbox data
    By Welder in forum C Programming
    Replies: 20
    Last Post: 11-02-2007, 12:48 AM
  4. What's wrong with my search program?
    By sherwi in forum C Programming
    Replies: 5
    Last Post: 04-28-2006, 10:57 AM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 04:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21