在C的typedef枚举解释 [英] typedef enum explanation in c
问题描述
我在看一个微控制器上的ADC的头文件和下面的code是它。
I'm looking at a header file for an ADC on a micro controller and the following code is in it.
/**
* ADC channels type.
*/
typedef enum {
ADC_CH_0,
ADC_CH_1,
ADC_CH_2,
ADC_CH_3,
ADC_CH_4,
ADC_CH_5,
ADC_CH_6,
} adc_channel_t;
而在main.c中的ADC有code的以下行
And in the main.c for the ADC there is the following line of code
adc_channel_t channels[] = {ADC_CH_4, ADC_CH_5};
我想知道为什么你需要为ADC宣布新的数据类型?又是什么类型定义枚举意味着什么呢?
I was wondering why would you need declare new data types for the ADC? and what does typedef enum mean?
感谢
推荐答案
作为补充由ARTM的答案的typedef
在<$ C $前面添加C>枚举,以缓解使用的枚举
。了宣言看上去像这个:
As a complement to the answer by artm the typedef
is added in front of the enum
, to ease the use of the enum
. Had the declaration looked like this instead:
enum adc_channel_t {
ADC_CH_0,
ADC_CH_1,
ADC_CH_2,
ADC_CH_3,
ADC_CH_4,
ADC_CH_5,
ADC_CH_6,
};
然后行 adc_channel_t频道[] = {ADC_CH_4,ADC_CH_5};
将不得不写为:
enum adc_channel_t channels[] = {ADC_CH_4, ADC_CH_5};
的的typedef
让我们忽略了枚举
在每次使用的类型。
The typedef
allows us to ignore the enum
at every use of the type.
使用有用的常量往往是$ pferred了幻数P $,虽然这似乎在这种情况下,常量给一点额外的信息有点怪。因为枚举作为额外的说明但它会是有用的。比如你的IDE将期望类型的值 adc_channel_t
将能够建议道: ADC_CH_0
到 ADC_CH_6
这可能是值的有效范围,而不是简单地告诉你使用一个号码。
Using useful constants is often preferred over "magic numbers", though it might seem a bit strange in this case the constants give little extra information. It can however be useful since the enumerator serves as extra description. For instance your IDE which will expect a value of type adc_channel_t
will be able to suggest the channels: ADC_CH_0
through ADC_CH_6
that might be the valid range of values, instead of simply telling you to use a number.
这篇关于在C的typedef枚举解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!