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;
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};
I was wondering why would you need declare new data types for the ADC? and what does typedef enum mean?
Thanks
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,
};
Then the line adc_channel_t channels[] = {ADC_CH_4, ADC_CH_5};
would have to be written as:
enum adc_channel_t channels[] = {ADC_CH_4, ADC_CH_5};
The typedef
allows us to ignore the enum
at every use of the type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With