zoukankan      html  css  js  c++  java
  • C语言中的共用体(union)和枚举(enum)

    1 union

    union Data{

    int i;

    char ch;

    float f;

    }a={1, 'a', 1.5};  //错误

    union Data a = {16};  //正确

    union Data a = {.ch = ‘j’};  //正确

    在什么情况下使用共用体类型的数据?往往在数据处理中,有时需要对同一段空间安排不同的用途,这时用共用体类型比较方便,能增加程序处理的灵活性。

    例如,学生的数据包括:姓名、号码、性别、职业、班级

               教师的数据包括:姓名、号码、性别、职业、职务

    要求用同一个表格来表示。

    C语言核心代码

    1 struct{
    2     int num;          //成员 编号
    3     char name[10];    //成员 姓名
    4     char sex;         //成员 性别
    5     union{            //声明无名共用体类型
    6         int class;    //成员 班级
    7         char position[10];//成员 职务
    8     }category;
    9 }person[2];
    View Code

    2 enum

    一个变量只有几种可能的值,则可以定义为枚举(enumeration)类型。

    enum Weekday{sun=7, mon=1, tue, wed, thui, fri, sat} workday, weak_end;  {}内,tue为2,wed为3,thu为4……

    enum Weekday{sun, mon, tue, wed, thui, fri, sat} workday, weak_end;    {}内,sun=0, mon=1, tue为2,wed为3,thu为4……。

    在枚举类型中,第一个枚举元素的值为0

    enum escapes  //转移符

        BELL      = 'a',
        BACKSPACE = '',
        HTAB      = ' ',
        RETURN    = ' ',
        NEWLINE   = ' ', 
        VTAB      = 'v',
        SPACE     = ' '
    };

     1 #include<stdio.h>
     2 
     3 
     4 
     5 enum
     6 
     7 { 
     8 
     9     BELL          = 'a',
    10 
    11     BACKSPACE = '',
    12 
    13     HTAB         = '	',
    14 
    15     RETURN      = '
    ',
    16 
    17     NEWLINE    = '
    ', 
    18 
    19     VTAB         = 'v',
    20 
    21     SPACE       = ' '
    22 
    23 };
    24 
    25 
    26 
    27 enum BOOLEAN { FALSE = 0, TRUE } match_flag;
    28 
    29 
    30 
    31 void main()
    32 
    33 {
    34 
    35     int index = 0;
    36 
    37     int count_of_letter = 0;
    38 
    39     int count_of_space = 0;
    40 
    41 
    42 
    43     char str[] = "I'm Ely efod";
    44 
    45 
    46 
    47     match_flag = FALSE;
    48 
    49 
    50 
    51     for(; str[index] != ''; index++)
    52 
    53         if( SPACE != str[index] )
    54 
    55             count_of_letter++;
    56 
    57         else
    58 
    59         {
    60 
    61             match_flag = (enum BOOLEAN) 1;
    62 
    63             count_of_space++;
    64 
    65         }
    66 
    67 
    68     printf("%s %d times %c", match_flag ? "match" : "not match", count_of_space, NEWLINE);
    69 
    70     printf("count of letters: %d %c%c", count_of_letter, NEWLINE, RETURN);
    71 
    72 }
    View Code

     

     

  • 相关阅读:
    codeforces_1075_C. The Tower is Going Home
    leetcode_Stone Game_dp_思维
    leetcode_Counting Bits_dp
    Divide and Conquer_1.最大连续子数组
    python_MachineLearning_感知机PLA
    IIS中启用gzip压缩(网站优化)
    asp.net运行机制图
    asp.net 的那点事(2、浏览器和一般处理程序)
    asp.net 的那点事(1、当用户在浏览器地址栏输入了网址后,发生了什么?)
    android环境搭配 运行android sdk manager时出现错误问题解决
  • 原文地址:https://www.cnblogs.com/wxwhnu/p/11523214.html
Copyright © 2011-2022 走看看