[C ++ Basics] 038 _ effect of joint type declaration position on its value

Source: Internet
Author: User

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.

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.