Thread: struct vs. union

  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,897
    >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, 02: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-01-2007, 11:48 PM
  4. What's wrong with my search program?
    By sherwi in forum C Programming
    Replies: 5
    Last Post: 04-28-2006, 09: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, 03:00 PM