Introduction to Computer Science - C++

Enumeration Types

An enumeration type is a user defined data type which can be assigned only a predefined set of constant integer values (not decimal point values). The constant values it can be defined as are listed and named by the programmer. These values are named constants, similar to defines.

Here is an example of an enum declaration:

enum Error {DIVIDEBYZERO, NOFILE, ACCESSDENIED, NORESOURCE};

This will create a user define type called Error which can be assign the values DIVIDEBYZERO, NOFILE, ACCESSDENIED, or NORESOURCE where DIVIDEBYZERO == 1, NOFILE == 2, ACCESSDENIED == 3, and NORESOURCE == 4.

Just as with classes, I can create instances of my enumeration by inserting instance identifiers after the closing brace. The following will create 3 instances (a, b and c) of the enum class Error:

enum Error {DIVIDEBYZERO, NOFILE, ACCESSDENIED, NORESOURCE}a,b,c;

By convention, we use all capital letters for values of enums, just as we do with defines. And we capitalize enum names, just like class names.

In order to create an instance of this type I need to write something like this:

Error myerrror;
Then I can give it a value like this:
myerror = NORESOURCE;

Thus you can see that the values work like defines. I use names, but I really mean integers. But I can only assign my enum instance names listed in the declaration, I cannot assign the enum instance the literal integer equivalent of one of the names listed in the declaration.

myerror = 4;
will not compile. And certainly neither will
myerror = 5;
But I can compare the value if a enum instance to a literal integer.

By default, the values assigned to an enumeration start at zero (0) and ascend by increments of one. If I want to start at a different number, one (1) for example, I simply need to define the first value to be that number (one) and all following values will increment upward from there. For example, this will give the months of the year the values 1 through 12:

enum Months { JAN=1, FEB, MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC};
I can also assign completely unrelated values to my enum, as in the example below. The values must be integers, and not decimal values. (Though, for example, 'a' is allowed as a value since it is interpretted as its ascii value, 97.)


#include "stdio.h"
int main()
{
enum Error {DIVIDEBYZERO =4 , NOFILE=6 , ACCESSDENIED=18, NORESOURCE=17}a, b;
a = NOFILE;
    // a=6; will not compile, can only assign listed identifiers
if (a == 6 )
    {

    printf("File does not exist.\n");

    }
return 1;
}

© Nachum Danzig October 2011