Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef enum explanation in c

Tags:

c

typedef

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

like image 227
ultrasonic bananna Avatar asked Dec 07 '15 11:12

ultrasonic bananna


1 Answers

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.

like image 86
Tommy Andersen Avatar answered Oct 26 '22 00:10

Tommy Andersen