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.