Previous: 5.3.1 Data Type void
Up: 5.3 Scalar Data Types
Next: 5.3.3 Defining User Types: typedef
Previous Page: 5.3.1 Data Type void
Next Page: 5.3.3 Defining User Types: typedef
The data type, enum (for enumeration) also allows improvement in program clarity by specifying a list of names, the enumeration constants, which are associated with constant integer values. It is similar to using #define directives to define constant integer values for a set of symbolic names; however, with enum the compiler can generate the values for you, and may check for proper use of enum type variables. A variable of enum type is declared as follows:
enum { FALSE, TRUE } flag;The variable, flag, is defined here to be of a type which can take on the two enumerated constant values, FALSE and TRUE. Normally, enumeration constants are identifiers whose values start at zero and increase in sequence: here, FALSE is 0, and TRUE is 1. However, the enumeration can have explicit constant values specified in the enumeration:
enum { SUN = 1, MON, TUE, WED, THU, FRI, SAT } day;Here, SUN is associated with value 1, and the rest of the names have values in increasing sequence: MON is 2, TUE is 3, and so on until SAT which is 7. The variable, day can hold any of the enumerated values.
An enumeration type can be given a tag, i.e a name which can be used later to declare variables of that tagged enumeration type. For example, we can name an enumeration:
enum boolean { FALSE, TRUE };where the name boolean can then be used to declare variables of that enumeration type:
enum boolean flag1, flag2;This declaration defines variables, flag1 and flag2, which are of a type specified by the boolean enumeration; that is, flag1 and flag2 can have values FALSE or TRUE. It is also possible to specify a tag and declare variables in the same declaration:
enum boolean {FALSE, TRUE} done; enum boolean found;The first declaration specifies a tag, boolean, for the enumeration as well as declaring a variable, done of this type. The second declaration defines a variable, found, of the enumeration boolean type. Here is a function, digitp(), that returns a boolean value to the calling function. (The calling function must also declare the enumeration in order to use the returned value correctly).
enum boolean { FALSE, TRUE };enum boolean digitp(char c) { if (c >= '0' && c <= '9') return TRUE; else return FALSE; }
Remember, the value of an enum type variable is an integer. An enumerated data type is primarily a convenience for writing the source code; information about the symbolic names are not retained at run time. For example, if we were to execute a statement:
printf("digitp returns %d\n",digitp('0'));it would print