Thread: Unions

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    8

    Unions

    Hi, doing an assignment that involves floating point numbers and integers. What I am supposed to do is make the program use either integers or floating point numbers depending on the input from the main function. This is not user input, but coded into main. I had the idea to use a union to help with this, but I am not sure about that, or how to go about it. I was told that I was also, along with the union, supposed to come up with a function to set the variable type. Right now, and I am not sure this is even remotely correct is:

    union Values{
    float x;
    int y;
    };

    If you could tell me how to manipulate the union/data so that the program would use the correct variable type, that would be great. thanks.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    You need an additional member to help you decide what you've got stored.

    Code:
    struct Values {
      enum { isInt, isFloat } type;
      union {
        int iVal;
        float fVal;
      };
    };
    
    Values var;
    var.type = isInt;
    var.iVal = 1;
    
    if ( var.type == isInt ) {
        // do int things
    } else {
       // do float things
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unions of the same size and pointers
    By holychicken in forum C Programming
    Replies: 9
    Last Post: 10-06-2008, 03:29 PM
  2. Structures, Unions and Classes
    By Makoy in forum C++ Programming
    Replies: 2
    Last Post: 02-23-2004, 02:57 PM
  3. Structures - Unions
    By AProg in forum C Programming
    Replies: 16
    Last Post: 05-27-2003, 12:43 AM
  4. unions problems!
    By nextus in forum C++ Programming
    Replies: 3
    Last Post: 01-12-2003, 04:04 AM
  5. Unions in c++
    By The Gweech in forum C++ Programming
    Replies: 5
    Last Post: 08-06-2002, 08:14 AM