Example of use of the Common Body Union (c language)

Source: Internet
Author: User

I have never understood the use of the common Body Union when I was studying C in school. After work only to find some of its magical, the proportion is as follows:

1. To make it easier to read the code.

For example, to write a 3 * 3 matrix, you can write:
[ Note: The following is marked with the red part of the place is later added, thank you yrqing718 reminder! ]

  1. struct Matrix
  2. {
  3. Union
  4. {
  5. struct
  6. {
  7. float _f11, _f12, _f13, _f21, _f22, _f23, _f31, _f32, _f33;
  8. };
  9. float f[3][3];
  10. }_matrix;
  11. };
  12. struct Matrix m;

These two things together use the same space, so there is no space wasted, when the need for the overall matrix can be sufficient
M._MATRIX.F (such as a pass-through, or an overall assignment, etc.), the need to use a few of the elements can be used in m._matrix._f11 as can be avoided with m.f[0][0] (this is not intuitive, and easy error).

2. Use on coercion type conversions (easier to read than coercion type conversions)
Here are a few examples:

(1). The inference system uses big endian or little endian (the definition of which we can check the relevant information on the Internet, this slightly)

  1. #define TRUE 1
  2. #define FALSE 0
  3. #define BOOL INT

  4. BOOL Isbigendian ()
  5. {
  6. int i = 1; / * i = 0x00000001*/
  7. char C = * (char *) &i; /* Note cannot be written as char C = (char) i; */
  8. return (int) c! = i;
  9. }
Assuming it is little endian byte order, that i = 1; the memory is placed from small to large: 0x01 0x00 0x00 0x00, if, according to the starting address of I into the char * Mode (1 bytes) access, that is, C = 0x01;
Vice versa

It may not seem very clear to look at this:

      bool  isbigendian (
    1. {
    2.     union
    3.     {
    4.         int  i;
    5.         char  c;
    6.     }test;
    7.     
    8.     test.c = 2;
    9.  
    10.     return  test.i != 2;

The union is used here to control this shared layout, and there is a knowledge that the members C and I in the Union are aligned from the low address. The same can get such results, and without conversion, clear some.

What, do not think clear?? Then look at the following examples:

(2). Replace the long long type value under little endian with the value of the big endian type. It has been known that the system provides the following Api:long htonl (long LG); The function is to change the whole byte order into big endian. The following approach is therefore obtained:

  1. Long long HTONLL (long long LG)
  2. {
  3. Union
  4. {
  5. struct
  6. {
  7. long Low;
  8. long High;
  9. }val_1;
  10. Long long val_2;
  11. }val_arg, Val_ret;
  12. if (Isbigendian ())
  13. return LG;
  14. val_arg.val_2 = LG;
  15. Val_ret.val_1.low = htonl (Val_arg.val_1.high);
  16. Val_ret.val_1.high = htonl (Val_arg.val_1.low);
  17. return val_ret.val_2;
  18. }

It's easier to make a simple sketch of the memory structure.

(3). To understand the layout of C + + classes, look at the following example. There are for example the following classes:

    1. class Test
    2. {
    3. Public:
    4. float getfval () { return F;}
    5. Private:
    6. int i;
    7. Char c;
    8. float F;
    9. };
    10. Test T;

You cannot add code to class test to assign a value of 7.0f to f in an object.

  1. class test_cpy
  2. {
  3. Public:
  4. float getval () { return F;}
  5. float setval (float f) { this->f = f;}
  6. Private:
  7. int i;
  8. Char c;
  9. float F;
  10. };
  11. ....
  12. int Main ()
  13. {
  14. Test T;
  15. Union
  16. {
  17. Test T1,
  18. test_cpy T2;
  19. }test;
  20. Test.t2.setVal (7.0f);
  21. t = test.t1;
  22. ASSERT (t.getval () = = 7.0f);
  23. return 0;
  24. }

Description: Because of the addition of the member functions of the class, the layout of the object for that class is basically the same. It is therefore possible to write a class test_cpy the same structure as the test class, and a member function setval, and then aligned with the Uinon structure, can assign a value to a private variable. (Such a method may fail in the virtual machine class and virtual function mechanism, it is not portable) as to the specific discussion, on the Internet, this sample is not practical use in practice, is only used to investigate the use of this memory layout.

The union is used more in the code underlying the operating system, because it is convenient and intuitive in the memory-sharing layout. So network programming, protocol analysis, some of the kernel code used in the Union are more understood, simplifying the design.

Example of use of the Common Body Union (c language)

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.