c语言枚举_C枚举

c语言枚举

C Enumeration or Enumerated Data Type

C enumeration is a user defined data type which consists of a list of names and each name corresponds to an integral constant. It increases the program readability as names are easy to read and maintain. Enumerated data type can be defined in C using “enum” keyword. The syntax is given below.

Syntax


Example

enum day {mon, tue, wed, thu, fri, sat, sun};


In above example we have defined an enumerated data type day. Now we have to declare variables of this data type. The variables can store any name present in the list of names. The variables can be declared in following way.


Above we have declared two variables. The variable can also be declared at the time of defining the enumerated data type. For doing this just write the variable name after the closing braces and before the semicolon.

As I have already told you that each name in the list corresponds to an integral value. By default the integral value starts with 0. In above example “mon” will corresponds to 0, “tue” will corresponds to 1, “wed” will corresponds to 2 and so on. We can also assign random integral values explicitly. It can be done in following way.

enum day {mon=5, tue=7, wed=8, thu=10, fri=15, sat=25, sun=19}; //example 1
enum day {mon=2, tue, wed, thu, fri, sat, sun}; //example 2


In first example I have assigned random values to each name. In second example I have assigned value to only first name i.e. mon=2. The rest names will be assigned values that increased successively by 1. Remember that the values must be integer only and two names can have same value.

Lets make one program to understand the concept of C enumerated data type.


Output

C Enumeration - Enumerated Data Type

Explanation

  1. First of all I have declared an enumerated data type day which contains list of names of days in a week.
  2. As I have not assigned values to these names explicitly so the compiler will assign them values starting from 0.
  3. Now I have declared two variables d1 and d2 of this enumerated data type and assigned them names from the name list.
  4. Now I am printing the variables. In first printf() statement the output is 1 because d1 contains “tue” and it corresponds to integer value 1.
  5. In second printf() statement the variable d2 contains “thu” which corresponds to integer value 3. As I have written d2+2 so it will be equal to 5.

This is all about C enumeration. If you have any doubts or find any mistake in above tutorial then please mention it by commenting below.

翻译自: https://www.thecrazyprogrammer.com/2015/02/c-enumeration.html

c语言枚举

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值