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

Source: Internet
Author: User

Joint

The difference between union and structure is that the structure applies a memory space for each field, and the union just applies a memory space and all the fields are saved in this space, the size of the space is determined by the longest in the field, and we begin to define a union

1 // Definition of Union 2 typedef union{3      Short count; 4     float weight; 5     float volume; 6 } quantity;

Combined use we can assign values in a number of ways

1typedefstruct{2     Const Char*color;3 quantity amount;4 }bike;5 6 intMain () {7     //to represent the number of bicycles with a union8Bike b={"Red",5};9printf"Bike color:%s count:%i\n", b.color,b.amount.count);Ten      //use a joint to represent the weight of a bicycle OneBike b2={"Red",. amount.weight=10.5}; Aprintf"Bike color:%s count:%f\n", b2.color,b2.amount.weight); -     return 0; -}

But it can be very easy to get into trouble when reading the values of the Union, for example, we saved a float type field, but it was read from the short field and got a value that was irrelevant to the expectation.

Enumeration

To avoid confusing the data types of fields like union, we can use enumerations

1#include <stdio.h>2 3 //definitions and struct classes for enumerations4typedefenumcolors{red,black,blue,green} colors;5 6 intMain () {7Colors favorite=BLUE;8printf"%i", favorite);9     return 0;Ten}

If you want to save more than one data type L union The enumeration is more appropriate, then to save multiple data, enumeration is more suitable than union

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

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.