A small summary of structure, position field and union

Source: Internet
Author: User
Tags switch loop

First, Structure:

1. Direct examples:

struct point{    int  x;     int y;} PT={; // Point is a struct name, can not be written, PT is a struct variable, and is initialized. 

2. Details to be aware of:

1) The structure type definition must end with a semicolon.

2) struct point in C is a struct type name, and a struct must be used when defining a variable, whereas C + + can define a variable directly with a struct, without structs.

3) C language structure in the body can not define functions, and C + + struct and class is basically a thing, only a little different, that is, the default variables in the struct, the function is public, and class is the default is private.

4) Alignment mode. The variables inside the structure need to be aligned when they are stored in memory, and should be noted when manipulating the pointer. An example of good understanding is that

#include <iostream>usingnamespace  std; struct i{    char  s;     int D;} P; int Main () {    cout<<sizeof(p) <<endl;  The result is 8    return0;}

Second, bit field:

The following reprint a blog, speak very well. Http://blog.sina.com.cn/s/blog_3d8529400100istl.html

While some information is stored, it does not need to occupy a full byte, only a few or one bits. For example, when storing a switching volume, there are only 0 and 12 states, with one binary. In order to save storage space and make processing simple, C language also provides a data structure, called "bit field" or "bit segment". The so-called "bit field" is to divide the binary in one byte into several different regions and describe the number of bits per region. Each domain has a domain name that allows operations to be performed by domain name in the program. This allows you to represent several different objects in a bits field of one byte. The definition of a bit field and the description of a bit-field variable are similar to the structure definition, in the form of:structbit domain struct name {bit field list}; The list of bit fields is in the form: type specifier bit domain name: bit field length For example:structbs{intA:8; intB:2; intC:6;}; The description of a bit-field variable is the same as the structure variable description. Can be defined by the first description, at the same time define the description or direct description of the three ways. For example:structbs{intA:8; intB:2; intC:6;} Data: Data is a BS variable, accounting for two bytes. Where bit domain A occupies 8 bits, bit domain B is 2 bits, bit field C is 6 bits. There are several explanations for the definition of bit fields:1. A bit field must be stored in the same byte and cannot span two bytes. If one byte has enough space left to hold another domain, the bit field should be stored from the next cell. You can also intentionally make a field start from the next unit. For example:structbs{unsigned A:4; Unsigned:0; Unsigned b:4; Unsigned c:4;} In this bit domain definition, a occupies the first byte of 4 bits, the latter 4 bits fill 0 means not to use, B starts with the second byte, occupies 4 bits, and C occupies 4 bits. 2because bit fields are not allowed to span two bytes, the length of the bit field cannot be greater than the length of one byte, that is, it cannot exceed the 8-bit binary. 3a bit field can have no bit domain name, and it is used only to fill or adjust the position. Nameless bit fields are not available. For example:structk{intA:1; int:2; intB:3; intC:2;}; From the above analysis, we can see that the bit field is essentially a type of structure, but its members are assigned by binary. The use of bit fields in bit fields is the same as the use of the struct members, and the general form is: bit field variable name • Bit domain name field allows output in various formats. Main () {structBS {unsigned A:1; Unsigned b:3; Unsigned c:4; } bit,*Pbit; BIT.A=1; bit.b=7; Bit.c= the; printf ("%d,%d,%d\n", bit.a,bit.b,bit.c); Pbit=&bit; Pbit->a=0; Pbit->b&=3; Pbit->c|=1; printf ("%d,%d,%d\n",pbit->a,pbit->b,pbit->c);} In the example program, the bit-domain structure BS is defined, and the three-bit domain is a,b,c. The variable bit for the BS type and pointer variable pbit to the BS type are described. This means that a bit field can also use pointers. Program of 9,Ten, 113 rows Assign values to three bit fields. (Note that the assignment cannot exceed the allowed range of this bit field) the 12th line of the program outputs the contents of three fields in an integer format. The 13th line sends the address of bit field variable bit to pointer variable pbit. The 14th row assigns a value to bit field A as a pointer to 0. The 15th row uses a compound bitwise operator"&=", the line is equivalent to: pbit->b=pbit->b&3 bit field B has a value of 7, and 3 for bitwise AND operation result is 3 (111&011=011, the decimal value is 3). Similarly, the compound bit operation is used in line 16th of the program"|="The reason to have a basic knowledge of dialysis such a column, is to tell everyone in detail the truth, rough things who understand, the training of internal strength for the master of the way. The previous content is defective, the specific also refer to the following article: C99 provisions int, unsigned int and bool can be used as bit field types, but the compiler has almost extended this to allow the existence of other types of type. The primary purpose of using bit fields is to compress the storage, with the following approximate rules: 1) If the adjacent bit field field is of the same type and its bit width is less than the type sizeof size, then the field will be stored next to the previous field until it cannot be accommodated, and 2) if the adjacent bit field field has the same type, but its bit width is greater than the type sizeof size, Then the next field will start from the new storage unit, its offset is an integer multiple of its type size; 3) If the adjacent bit field fields have different types, the specific implementation of each compiler differs, VC6 take the uncompressed way, dev-c++ take compression; 4) If the bit field fields are interspersed with non-bit fields, The compression is not performed; 5The   total size of the entire struct is an integer multiple of the size of the widest base type member.  typedefstructaa{unsignedCharB1:5; unsignedCharc2[5; unsignedCharB3:5; unsignedCharB4:5; unsignedCharB5:5;} AA;sizeof(AA) =5but in fact it only uses 25 bits, or 4 bytes, (1) typedefstructaa{unsignedintB1:5; unsignedintB2:5; unsignedintB3:5; unsignedintB4:5; unsignedintB5:5;} AA; (2) typedefstructaa{unsignedintc1[5; unsignedintB2:5; unsignedintc3[5; unsignedintB4:5; unsignedintB5:5; unsignedintB6:5; unsignedintB7:5;} AA; (1) is 5 members, according to the first rule, a total of 25 bits, according to the fifth rule, namely sizeof (AA) =4Now add the members to 7, reference (2), by the first rule, a total of 35 bits, according to the fifth rule, namely sizeof (AA) =8, let's look at an example:structtest1{CharA:1;Char:2;LongB:3;CharC:2;};intLen =sizeof(test1); For the above example, the value of Len should be 12. Explanation is as follows: First, the longest type bit width as the offset, the longest is a long type, 4 bits, so the different types should be 4 byte offset, that is, the test1 should be a 4-byte integer multiple. CharA:1;//to store with a single byteChar:2;//airspace. Because the type of the previous a is the same, and the bit width addition of the two bit fields is still less than 8 bits, it is still represented by 1 bytesLongB:3;//the bit width of type long is 4 bytes, which is different from the preceding char type, so B and a are offset by 4 bytes, and they automatically complement 3 bytesCharC:2;//because C and B are different types, they are offset by the longest long type of bit width in test1, so although Char takes only 1 bytes, it's enough.//but it still takes 4 bytes. The total is 12 bytes. ///////////////////////structS1 {intI8; intJ:4; intA:3; Doubleb;  }; structS2 {intI8; intJ:4; Doubleb; intA:3;  }; printf ("sizeof (S1) =%d\n",sizeof(S1)); printf ("sizeof (s2) =%d\n",sizeof(S2)); Result: -, -first struct S1 {intI8; intJ:4; intA:3; Doubleb;  }; Theoretically, the first is I in the position relative to 0, accounting for 8 bits of a byte, and then, J is in the position relative to a byte, because the number of bytes in a position is a multiple of 4 bits, so do not align, put there, and then a, to the position of the 3-bit multiple relationship, so to move a bit, Put down in 15 position, currently a total of 18 bits, the conversion is 2 bytes 2 bits, because the double is 8 bytes, so in the relative 0 if the position of 8 bytes is dropped, so the position from 18 to 8 bytes is ignored, directly placed in 8 byte position, therefore, The total is 16 bytes. 

Here only one sentence, that is, for the general internal structure of the computer, the members of the bit domain from a byte from the low to high storage.

Iii. Union:

The format can be seen in the following example, there are three points to note:

1. All members of the Union share a common memory, and the change of one member changes the value of all other members.

2. The first address of all members is the same.

3. The alignment satisfies all members.

See Example:

Union value{    char s[9];     int N;     Double D;} data; // its size is 16. The size of the consortium must meet two conditions: 1) large enough to accommodate the widest member; 2) the size can be divisible by the size of all the basic data types it contains. 

Iv. enumeration:

1. Define enum type: Eg:enum color{black,blue,red,white};

Define enumeration constants: Eg:enum color C1;c1=blue;

Both can be together: Eg:enum Color{black,blue,red,white} C1;

2. Enumeration constants store the corresponding ordinal number in memory, which is the integer value. In other words, the essence is the integer value, so the method is consistent with the integer. The default sequence number starts at 0.

When you define an enumeration type, you can display the ordinal that modifies the enumeration constant.         Eg:enum Color{black,blue,red=5,green}; Then Black (0), Blue (1), Red (5), Green (6)

3.enum can be used as an integral type of data.

such as for Loop: for (cl=black;cl<=white;cl++) {...}

such as the switch loop:

Switch (C1)

{

Case Black: ...

Case RED:.

...

}

A small summary of structure, position field and union

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.