Thread: 'union' keyword

  1. #1
    Shadow12345
    Guest

    'union' keyword

    I was told that the 'union' keyword allows you to be able to assign two variables to the same block of memory, but I'm not sure how you use it, and I was hoping someone could tell me.
    Thanks in advanced;

  2. #2
    Funniest man in this seat minesweeper's Avatar
    Join Date
    Mar 2002
    Posts
    798
    What you say is correct and I once came across an example that demonstrated it as follows:

    The example was to reverse the byte ordering of a long.

    A long is 4 bytes which is equal to an array of 4 characters. So a solution was to create a union consisitng of a long and an array of 4 chars. These will be laid over one another in memory. Then assign a value to the long, the 4 bytes of this value will each take up one of the chars in the array. Then simply reverse the order of the chars in the array and you have successfully reversed the byte order of the long.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sizeof union question
    By noops in forum C Programming
    Replies: 13
    Last Post: 06-06-2008, 11:56 AM
  2. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  3. "generic" union or something
    By Raven Arkadon in forum C++ Programming
    Replies: 2
    Last Post: 12-05-2005, 09:55 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Sorting a Union
    By andy in forum C Programming
    Replies: 4
    Last Post: 11-21-2001, 10:12 AM