BP-5-1 Enumeration Type

Chapter 05 Compound Data Type - Constructed Type

1. Enumeration Type

  • Type Construction
enum <enumeration-type-name> {<enumerration-value-list>};

Enumeration type name is an identifier, which identifies the name of an enumeration type, which can be left out.

Enumeration value list is a list of values separated by commas, and the values in it are integral symbolic constants, and each of them has a corresponding integer value which by default start from 0.

Enumeration variable definition:

<enumeration-type-name> <variable-list>;
//or
enum <enumeration-type-name> <variable-list>;

We can also define a enumeration type as well as defining a enumeration variable.

enum Day {SUN, MON, TUE, WED, THU, FRI, SAT} d1, d2, d3;

If we leave out the name of the enumeration type, we must define the variable just as we define the type or we’ll never have access to the type again because it’s anonymous.

  • Manipulation of Enumeration Type

    • Assignment

      • We can’t use assignment between variables of different enumeration types

      • If we assign an integer to a enumeration type variable, we assign the value in its value set corresponding to the integer. If there’s none, an error will be raised.

    • Comparison

      • Compare the integer corresponding to it.
    • Output

      • We can’t input a value to an enumeration variable
      • But we can output an enumeration value in the form of its corresponding integer.
      • So, if we want to input a enumeration value, there should be some special methods:
      #include <iostream>
      using namespace std;
      
      enum Day {SUN, MON, TUE, WED, THU, FRI, SAT};
      
      int main(){
          Day d;
          int i;
          cin >> i;
          switch (i){
              case 0: d = SUN; break;
              case 1: d = MON; break;
              case 2: d = TUE; break;
              case 3: d = WED; break;
              case 4: d = THU; break;
              case 5: d = FRI; break;
              case 6: d = SAT; break;
              default: cout << "Input Error!" << endl; return -1;
          }
          return 0;
      }
      
      //another way
      if (i < 0 || i > 6){
          cout << "Input Error!" << endl;
          return -1;
      }
      else
          d = (Day)i; //exeplicit type reversion
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值