A function is used to determine whether your computer is a small-end storage or a large-end storage.

Source: Internet
Author: User

Today, I saw a small program in unix network programming, which is very enlightening.

Int check_cpu ()

{
Union {
Short;
Char B;
} C;
C. a = 1;
Return c. B = 1;

}

If it is a small-end storage, 1 is returned, and the large-end storage returns 0.

I feel that this function is clever and uses the characteristics of union to determine the memory storage format.

Union purpose: Different Types of variables occupy the same memory;

Struct length: equal to the length of the longest member variable;

In addition, to further understand union, you can run the following program and analyze the results.

Void main ()
{
Union
{
Int I;
Struct {
Char first;
Char second;
} Half;
} Number;

// Start with Part 1
Number. I = 0x4241;
Printf ("% c \ n", number. half. first, number. half. second );

// Start with Part 2
Number. half. first = 'a ';
Number. half. second = 'B ';
Printf ("I = % x \ n", number. I );

}

Output result

AB

I = 4241.

If part 1 and part 2 in the above Code are reversed, it may not be the result, because the number of the local variable is not initialized. If the initialization is zero, it is okay, otherwise it will not be the result above, therefore, the problem is that the local variable is different from the global variable. The global variable system will give you the default initialization value, but the local variable will not.

In addition, the int type is 4 bytes. If you change the value to short, there is no need to assign the initial value to zero.

Related Article

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.