The Association Union's Introductory course in C language programming _c language

Source: Internet
Author: User

Federation (Union) is a special data type in C language that can store different types of data in the same memory location. You can define a consortium to use many members, but only one part can contain the value given at any time. The consortium provides an efficient way to use the same storage location for multiple purposes.

Define a consortium
to define a federation, you must use a union statement that is very similar to defining a structure. A consortium declaration defines a new data type, with more than one member of the program. The format of the Consortium declaration is as follows:

Union [Union Tag]
{member
  definition;
  Member definition;
  ...
  member definition;
} [One or more union variables]; 

The union tag is optional, and each member is defined as a normal variable definition, such as int i; and float F; Or the definition of any other valid variable. At the end of the Federation definition, before the last semicolon, you can specify the union of one or more variables, but it is optional. Here the definition of a data union type has three members I, F, and Str:

Union Data
{
  int i;
  float F;
  Char str[20];
} Data 

Now, data type variables can store integers, a floating-point number, or a character string. This means that a single variable structure, the same storage unit, can be used to store multiple types of data. You can use any built-in or user-defined data type as needed within the Union.

The memory consumed by union is large enough to hold the largest member of the consortium. For example, the data type in the example above will consume 20 bytes of storage, because this is the maximum space that is occupied by the text string. The following example shows the total memory size of the joint above:

#include <stdio.h>
#include <string.h>
 
Union Data
{
  int i;
  float F;
  Char str[20];
 
int main ()
{
  union data data;    

  printf ("Memory size occupied by data:%d
", sizeof (data));

  return 0;
}

Let's compile and run the above program, which will produce the following results:

Memory size occupied by data:20

Accessing Consortium members
to access any member of the Federation, we use the member access operator (.). The member access operator is encoded as a federation variable name and member, and the Union keyword is used to define a variable of the federation type. The following is an example to explain the use of a consortium:

#include <stdio.h>
#include <string.h>
 
Union Data
{
  int i;
  float F;
  Char str[20];
 
int main ()
{
  union data data;    

  DATA.I = ten;
  DATA.F = 220.5;
  strcpy (DATA.STR, "C programming");

  printf ("Data.i:%d
", data.i);
  printf ("DATA.F:%f
", DATA.F);
  printf ("Data.str:%s
", data.str);

  return 0;
}

Let's compile and run the above program, which will produce the following results:

data.i:1917853763
data.f:4122360580327794860452759994368.000000
data.str:c Programming

Here, we can see that the consortium members I and F values are corrupted because the values assigned to the variable end value are occupied by the memory location if the value of the STR member is well printed. Now, let's take a look at the same example again, we'll use a variable at the same time, and it's the main purpose of the consortium:

#include <stdio.h>
#include <string.h>
 
Union Data
{
  int i;
  float F;
  Char str[20];
 
int main ()
{
  union data data;    

  DATA.I = ten;
  printf ("Data.i:%d
", data.i);
  
  DATA.F = 220.5;
  printf ("DATA.F:%f
", DATA.F);
  
  strcpy (DATA.STR, "C programming");
  printf ("Data.str:%s
", data.str);

  return 0;
}

Let's compile and run the above program, which will produce the following results:

Data.i:10
data.f:220.500000
data.str:c Programming

Here, all the members get printed very well because a part is used once.

Application Occasions
Federation (Union) can be used when multiple data requires shared memory or when multiple data is taken one at a time. In the book C programming Language is described in this way:

1) A consortium is a structure;

2 The offset of all its members relative to the base address is 0;

3 This structure space to be large enough to accommodate the most "wide" members;

4 its alignment should be suitable for all the members;

These four descriptions are explained below:

Because all members of a consortium share a memory, the first address of each member is 0 higher than the base address of the consortium variable, that is, all members have the same first addresses. To allow all members to share a memory, the space must be sufficient to accommodate the widest member of those members. For this "alignment to fit all members" means that it must conform to the alignment of all members themselves.

The following examples illustrate:

such as Consortia

Union U
{
  char s[9];
  int n;
  Double D;
};

s accounts for 9 bytes, n is 4 bytes, and D is 8 bytes, so it requires at least 9 bytes of space. However, its actual size is not 9, and the operator sizeof tests its size to 16. This is because there is a problem of byte alignment, 9 can neither be divisible by 4 nor divisible by 8. So the bytes are added to 16 so that it fits all the members ' own alignment. It can be seen from here that the space occupied by the consortium depends not only on the widest member, but also on all members, that is, its size must meet two conditions: 1 the size is large enough to accommodate the widest member, and 2 the size can be divisible by the size of all the base data types it contains.

Test program:

/* Test Consortium 2011.10.3*/

#include <iostream>
using namespace std;

Union U1
{
  char s[9];
  int n;
  Double D;
};

Union U2
{
  char s[5];
  int n;
  Double D;
};

int main (int argc, char *argv[])
{
  U1 u1;
  U2 U2;
  printf ("%d\n", sizeof (U1));
  printf ("%d\n", sizeof (U2));
  printf ("0x%x\n", &u1);
  printf ("0x%x\n", &u1.s);
  printf ("0x%x\n", &U1.N);
  printf ("0x%x\n", &u1.d);
  U1.n=1;
  printf ("%d\n", U1.s[0]);
  printf ("%lf\n", u1.d);
  unsigned char *p= (unsigned char *) &u1;
  printf ("%d\n", *p);
  printf ("%d\n", * (p+1));
  printf ("%d\n", * (p+2));
  printf ("%d\n", * (p+3));
  printf ("%d\n", * (p+4));
  printf ("%d\n", * (p+5));
  printf ("%d\n", * (p+6));
  printf ("%d\n", * (p+7));
  return 0;
}

The output results are:


8
0x22ff60
0x22ff60
0x22ff60
0x22ff60
1
0.000000
1
0
0
0
204
0
Please press any key to continue ...

For sizeof (u1) = 16. Because s occupies 9 bytes in U1, N is 4 bytes, and D is 8 bytes, it requires at least 9 bytes. The basic data type it contains is char,int,double, which occupies 1,4,8 bytes, and in order for the U1 space to be divisible by 1,4,8, the byte must be padded to 16, so sizeof (U1) =16.

For sizeof (U2) = 8. Because s occupies 5 bytes in U2, N is 4 bytes, and D is 8 bytes, it requires at least 8 bytes. It contains the basic data types of char,int,double, respectively, 1,4,8 bytes, in order to make the size of the U2 space can be 1,4,8 divisible, no need to fill bytes, because 8 itself can meet the requirements. therefore sizeof (U2) = 8.

As can be seen from the base address of each member printed out, the base address of each member in the federation is the same, equal to the beginning of the Federation variable.

For U1.n=1, after assigning U1 N to 1, the first 4 bytes of memory in that segment are stored with 00000001 00000000 00000000 00000000

Therefore, the data of s[0] represents the data of the first unit, and the integer value is 1, so the result of the printout is 1.

As for the printed out D is 0.000000 willing to follow. Since the data for the first 4 bytes of the memory is known to be 00000001 00000000 00000000 00000000, print the results from above 48,204,64,0 can know that the data in the next 4 byte cell is 00110000 11001100 01000000 00000000, so the binary floating-point number that it represents is

00000000 01000000 11001100 00110000 00000000 00000000 00000000 00000001

For double data, 63rd Digit 0 is a sign bit, 62-52 00000000100 is a step, 0000 11001100 00110000 00000000 00000000 00000000 00000001 is the mantissa, The value of the mantissa is about 0, and the order is 4-1023=-1019, so the floating-point number represented is 1.0*2^ (-1019) =0.00000000000 ..., so the output is 0.000000.

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.