C Basic Knowledge----Union && enumeration && struct

Source: Internet
Author: User

struct struct structure body label (optional) {type 1 identifier 1; type 2 identifier 2; ...} (variable definitions are optional);
Union Union optional Label {type 1 identifier 1; type 2 identifier 2; .....
} optional variable definitions; Unions are similar to structs, but there are key differences in memory layout. Each member in the struct is stored sequentially, whereas in a union, all members are stored starting at an offset of 0 (where the position is overlapping), andat some point, only one member is actually stored in the address change.。
Enumeration (it is used to declare a set of named constants, which can be defined as enumerated types when there are several possible values for a variable) enum optional label {content ...} Optional variable definition; If an identifier in the list is assigned, then the next marker is 1 larger than the assigned value. However, for identifiers that are not previously defined, the names in the enumeration are typically always visible in the debugger and can be used while debugging code, while the constants defined by the # define macro are The general compile time is replaced.
Sample Program [CPP]View Plaincopyprint?
  1. #include <stdio.h>   
  2. struct s
  3. {
  4. int  A;
  5. Char  C;
  6. } S1;
  7. enum e
  8. {
  9. A,b=3
  10. }e1;
  11. Union u
  12. {
  13. int  A;
  14. int  b;
  15. Char      C;
  16. }U1;
  17. int Main (void)
  18. {
  19. S1.a=3;
  20. U1.a=3;
  21. u1.b=4;
  22. E1=b;
  23. printf ("struct:s1.a=%d\n", s1.a);
  24. printf ("enum:e1_b=%d\n", E1);
  25. printf ("union:u1.a.&=%x\n", &u1.a);
  26. printf ("union:u1.b.&=%x\n", &u1.b);
  27. }
Run results
From the running result, we know that all members of the Union share a storage address, and only one exists.

C Basic Knowledge----Union && enumeration && struct

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.