A very unusual union

Source: Internet
Author: User

A question sent to me by a friend is about union. I know that the Union clause indicates that several variables share the same memory location, saving different data types and variables of different lengths at different times. In union, all the common body members share one space and can only store the values of one of the member variables. But thisProgramThe results still surprised me. I have not figured out why it is like this.

The procedure is as follows:

 

# Include < Iostream >
Using   Namespace STD;

Struct   Byte
{
Unsigned Int A1: 1 ;
Int A2: 1 ;
Int A3: 1 ;
Int A4: 1 ;
Int A5: 1 ;
Int A6: 1 ;
Int A7: 1 ;
Int A8: 1 ;
};

Union B
{
Char C;
Struct   Byte Bit;
} Union_a;

Int Main ( Int Argc, Char   * Argv [])
{
Union_a.c =   ' A ' ;
Cout < (Union_a.bit.a7 + Union_a.bit.a1) < Endl;
Return   0 ;
}

The running result is 0.

Puzzled, so all the values of the a1-a8 are output. A1 = 1, A7 =-1, and others are 0.

Can someone analyze what is going on?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.