Results 1 to 3 of 3

Thread: Unions

  1. #1

    Thread Starter
    Hyperactive Member Amon Ra's Avatar
    Join Date
    Feb 2001
    Location
    In some cave on Uranus...
    Posts
    500

    Unhappy Unions

    I am currently working on the cplusplus.com tutorials. I am at the point where they talk about typedef's and unions...
    What are unions? I dont get it...could anyone explain to me?
    Thanks in advance.. =)
    Amon Ra
    The Power of Learning.

  2. #2
    Frenzied Member HarryW's Avatar
    Join Date
    Jan 2000
    Location
    Heiho no michi
    Posts
    1,827
    Unions are sets of variables that all occupy the same space in memory, so by changing one variable you change the others.

    For instance, you could have a union representing a 32-bit colour value in RGBA format like this:

    Code:
    union RGBA
    {   long value32;
         struct tagColourBytes
         {   unsigned char red;
              unsigned char green;
              unsigned char blue;
              unsigned char alpha
         } ColourBytes;
    }
    I'm not certain that would map directly onto an RGBA value (the byte values might be in reverse order) but that's the idea. You could then declare a variable to use the union like this:
    Code:
    RGBA myRGBAvar;
    // older C-style declaration would be this:
    // union RGBA myRGBAvar;
    You can then assign a 32-bit colour value to myRGBAvar.value32, and the values of myRGBAvar.ColourBytes.red, .green, .blue and .alpha would change because you have written to the same memory they occupy.
    Harry.

    "From one thing, know ten thousand things."

  3. #3
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    Yep, it's the other way round Harry R being least significant byte is last, they're stored ABGR
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width