Example of enumeration c in microcontroller programming

Enumeration allows defining a user data types in C language. For this purpose, a #define pre-processor is used, which allows for describing a set of constants. They allow reading and understanding program code much easier as you may define human readable types. For instance, using pre-processor we can define a simple numbers to be as follows:

#define zero 0
#define one 1
#define two 3

Define is a powerful tool for doing many different definitions in pre-processing stage of source code, but in C language, there is an alternative way of defining a user data types –  enumerating using keyword enum:

enum (zero=0,one, two);  //zero=0, one=1; two=2

By default, enumeration assigns values from zero and up.

You can use enumeration of new types as in following example:

int n;
enum (zero=0,one, two);
n=one; //n=1

Also, you can use an enum  to assign special characters to meaningful words like this:

enum escapes { BELL   = '\a', BACKSPACE = '\b', HTAB = '\t',
RETURN = '\r', NEWLINE = '\n', VTAB = '\v' };

or
enum boolean { FALSE = 0, TRUE };

An advantage of enum over #define is that it has scope, which means that the variable (just like any other) is only visible within the block it was declared.

Example:

main()
{
enum months {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};

enum months month; /* define 'month' variable of type 'months' */

printf("%d\n", month=Sep); /* Assign integer value via an alias * This will return a 9 */
}

Leave a Reply