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?