Let's take a look at two sections of code.
Segment 1:
1 union test{int b; char a[2];} shit; 2 3 int main(){ 4 5 shit.a[0]=10; 6 shit.a[1]=1; 7 cout<<sizeof(test)<<endl; 8 cout<<shit.b<<endl; 9 10 system("pause");11 return 0;12 }
Output:
4266 press any key to continue...
Segment 2:
1 int main(){ 2 union test{int b; char a[2];} shit; 3 shit.a[0]=10; 4 shit.a[1]=1; 5 cout<<sizeof(test)<<endl; 6 cout<<shit.b<<endl; 7 8 system("pause"); 9 return 0;10 }
Output:
4-859045622 press any key to continue...
The following is an explanation of the above two effects:
This is not a consortium problem, but a local variable and a global variable initialization problem.
The global variable is automatically initialized to 0, and the local variable is not (of course, the debug version of VC is initialized to 0 xcccccccc ).
When your A is a local variable, there are two bytes of A. I that are not assigned a value.
Initialization rules: the initialization part follows the same type and conversion rules as the value assignment statement. If a pure static object does not contain the initialization part during description, that is, it is not explicitly initialized, And it is initialized to zero by default (or empty characters ). Similarly, if the description of a static pointer object does not contain the initialization part, it is initialized as null by default. If an object with an automatic storage duration does not contain the initialization part during the description, the compiler will not perform implicit Initialization on it, so that the initial value is uncertain.
How did 266 come?
1. First, char and INT share 4 bytes of storage space.
2. Char occupies one byte
3. Therefore, the binary value of the stored value of. A is as follows: 0000000100001010
4. other values are considered as the int high, that is, 00000000000000000000000100001010.