Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Union

Union

Scheduled Pinned Locked Moved C / C++ / MFC
8 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • _ Offline
    _ Offline
    _8086
    wrote on last edited by
    #1

    union u { char ch[2]; int i; }; int main() { union u x={0,2}; cout<<x.ch<<"\n\n\n"; cout<<x.i<<endl; return 0; } Why does this print 512???:confused: What is this x={0,2}; exactly doing?

    ---------------------------- 286? WOWW!:-O

    D C I 3 Replies Last reply
    0
    • _ _8086

      union u { char ch[2]; int i; }; int main() { union u x={0,2}; cout<<x.ch<<"\n\n\n"; cout<<x.i<<endl; return 0; } Why does this print 512???:confused: What is this x={0,2}; exactly doing?

      ---------------------------- 286? WOWW!:-O

      D Offline
      D Offline
      David Crow
      wrote on last edited by
      #2

      The union looks something like this:

      -----------------------
      | 512 |

      | 00000010 | 00000000 |

      | 2 | 0 |

      "Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown

      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

      _ 1 Reply Last reply
      0
      • _ _8086

        union u { char ch[2]; int i; }; int main() { union u x={0,2}; cout<<x.ch<<"\n\n\n"; cout<<x.i<<endl; return 0; } Why does this print 512???:confused: What is this x={0,2}; exactly doing?

        ---------------------------- 286? WOWW!:-O

        C Offline
        C Offline
        CPallini
        wrote on last edited by
        #3

        Is doing politely what you asked with your code. The character array and the integer share the same memory space (at least the first two bytes), hence assigning one of the two will affect the other (you know that: it is a union, after all... :rolleyes:).

        _8086 wrote:

        union u x={0,2};

        Here the compiler initialise the ch member (this surpised a bit me) of the union with the characters having ASCII codes 0 and 2. Incidentally 0 corrensponds to string terminator so ch eventually contains an empty string, this explains the output of the

        _8086 wrote:

        cout<<x.ch<<"\n\n\n";

        line. Such a initialization affect also the integer (i) member, and since you computer is a little endian one, you get 0 * 2^0 + 2 * 2 ^ 8 = 512. This explains the output of the

        _8086 wrote:

        cout<<x.i<<endl;

        line. :)

        If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
        This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
        [My articles]

        _ 1 Reply Last reply
        0
        • D David Crow

          The union looks something like this:

          -----------------------
          | 512 |

          | 00000010 | 00000000 |

          | 2 | 0 |

          "Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown

          "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

          _ Offline
          _ Offline
          _8086
          wrote on last edited by
          #4

          Thanks.

          ---------------------------- 286? WOWW!:-O

          1 Reply Last reply
          0
          • C CPallini

            Is doing politely what you asked with your code. The character array and the integer share the same memory space (at least the first two bytes), hence assigning one of the two will affect the other (you know that: it is a union, after all... :rolleyes:).

            _8086 wrote:

            union u x={0,2};

            Here the compiler initialise the ch member (this surpised a bit me) of the union with the characters having ASCII codes 0 and 2. Incidentally 0 corrensponds to string terminator so ch eventually contains an empty string, this explains the output of the

            _8086 wrote:

            cout<<x.ch<<"\n\n\n";

            line. Such a initialization affect also the integer (i) member, and since you computer is a little endian one, you get 0 * 2^0 + 2 * 2 ^ 8 = 512. This explains the output of the

            _8086 wrote:

            cout<<x.i<<endl;

            line. :)

            If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
            This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
            [My articles]

            _ Offline
            _ Offline
            _8086
            wrote on last edited by
            #5

            Such a small thing has got this much hidden! That's all about that crazy union :). Thanks mate.

            ---------------------------- 286? WOWW!:-O

            L 1 Reply Last reply
            0
            • _ _8086

              Such a small thing has got this much hidden! That's all about that crazy union :). Thanks mate.

              ---------------------------- 286? WOWW!:-O

              L Offline
              L Offline
              led mike
              wrote on last edited by
              #6

              _8086 wrote:

              That's all about that crazy union

              Farout :beer:

              _ 1 Reply Last reply
              0
              • L led mike

                _8086 wrote:

                That's all about that crazy union

                Farout :beer:

                _ Offline
                _ Offline
                _8086
                wrote on last edited by
                #7

                lol :-D

                ---------------------------- 286? WOWW!:-O

                1 Reply Last reply
                0
                • _ _8086

                  union u { char ch[2]; int i; }; int main() { union u x={0,2}; cout<<x.ch<<"\n\n\n"; cout<<x.i<<endl; return 0; } Why does this print 512???:confused: What is this x={0,2}; exactly doing?

                  ---------------------------- 286? WOWW!:-O

                  I Offline
                  I Offline
                  Iain Clarke Warrior Programmer
                  wrote on last edited by
                  #8

                  Unions are powerful things, but until you realise that the parts share the same memory, you'll struggle. David's picture and Carlo's talk both help, I hope. They are very powerful in their limited way. Here's a sample of my code (no real secrets here):

                  union \_\_ChannelsOn
                  {
                  	BYTE	Mask;
                  	struct {
                  		BYTE	On1					: 1;
                  		BYTE	On2					: 1;
                  		BYTE	On3					: 1;
                  		BYTE	On4					: 1;
                  		BYTE	OnTOF				: 1;
                  		BYTE	Unused				: 1;
                  		BYTE	MasterOn			: 1;
                  		BYTE	ScanOn				: 1;
                  	} Bits;
                  } ChannelsOn;
                  

                  I have some hardware that has a command I send to it to turn channels on and off. I send a byte made up of flag bits. I could say:

                  __ChannelsOn c;
                  c.Mask = 1 << 3 | 1 << 7;
                  SendChannels (c);

                  or I say:

                  __ChannelsOn c;
                  c.Mask = 0;
                  c.Bits.On3 = 1;
                  c.Bits.ScanOn = 1;
                  SendChannels (c);

                  Both do the same thing - but which is more readable? They are also used to make the variant structure, used to talk with COM/VB. It's equivalent to:

                  struct VARIANT
                  {
                  int nType;
                  union {
                  int nInt;
                  long lLong;
                  DWORD dwDword;
                  BSTR bstr;
                  } Var;
                  };

                  I hope that helps a bit, Iain.

                  In the process of moving to Sweden for love (awwww). If you're in Scandinavia and want an MVP on the payroll (or happy with a remote worker), give me a job!

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups