'union' keyword

This is a discussion on 'union' keyword within the C++ Programming forums, part of the General Programming Boards category; I was told that the 'union' keyword allows you to be able to assign two variables to the same block ...

  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
    801
    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, 04:04 AM
  3. "generic" union or something
    By Raven Arkadon in forum C++ Programming
    Replies: 2
    Last Post: 12-05-2005, 08: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, 09:12 AM

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