C Language Learning 015: union and enumeration (enum), 015 enum

Source: Internet
Author: User

C Language Learning 015: union and enumeration (enum), 015 enum
Union

The difference between the Union and the structure is that the structure will apply for a piece of memory space for each field, while the Union only applies for a piece of memory space and all fields will be saved to this space, the size of this space is determined by the longest field. Next we will start to define a union.

1 // definition of union 2 typedef union {3 short count; 4 float weight; 5 float volume; 6} quantity;

In combination, we can assign values to the Union in many ways.

1 typedef struct {2 const char * color; 3 quantity amount; 4} bike; 5 6 int main () {7 // The number of bicycles in combination is 8 bike B = {"red", 5}; 9 printf ("bike color: % s count: % I \ n ", b. color, B. amount. count); 10 // indicates the weight of a bicycle in combination. 11 bike b2 = {"red ",. amount. weight = 10.5}; 12 printf ("bike color: % s count: % f \ n", b2.color, b2.amount. weight); 13 return 0; 14}

However, when reading the Union value, it is prone to problems. For example, we save a float type field, but read it through the short field to obtain the value that is not relevant to expectation.

Enumeration

To avoid confusion between the data types of fields like Union, we can use enumeration.

1 # include <stdio. h> 2 3 // enumeration definition and structure Class 4 typedef enum colors {RED, BLACK, BLUE, GREEN} colors; 5 6 int main () {7 colors favorite = BLUE; 8 printf ("% I", favorite); 9 return 0; 10}

If you want to save multiple data types, l Union enumeration is more suitable for storing multiple data types.

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.