{red, orange, yellow, green, blue, indigo, violet}
or
{Jack, Queen, King, Ace}
As for integer and characters, the ordering sequence of the set is defined
and is given by the order in which the identifiers appear in the
definition. Thus King > Queen has the value true. Each such value also
has a corresponding integer value, which usually starts as zero for the
first in the list (i.e. red==0 and Jack==0). Each successive value is one
greater than the preceding one (e.g. blue==4 and King==2).
It is possible to alter this sequence by explicitly assigning values to some or all of the names. Thus:
{StartV=30,SecV,ThirdV,FourV=40,FiveV}
would associate names to values as follows:
StartV==30,SecV==31,ThirdV==32,FourV==40,FiveV==41
Variables can be declared using this construct as follows:
enum Colours {red,orange,yellow,green,blue,indigo,violet};
Colours is a typename. It can be used to declare a variable which can (in
principle) only be used to hold values defined in the list following. Its
type is a sub-set of integer.
enum Colours MyColour;
declares MyColour as a variable which can have values from the set given in
the definition of Colour.
#include <stdio.h>
void main()
{
int Mark, Grade;
char MedCertificate;
scanf("%d",&Mark); /* Must be in range 0..100 */
if (Mark<45) Grade = 0; else
if (Mark<50) Grade = 1; else
if (Mark<55) Grade = 2; else
if (Mark<65) Grade = 3; else
if (Mark<80) Grade = 4; else
Grade = 5;
if((MedCertificate=getchar())=='y'&&Grade<5) Grade++;
switch (Grade) {
case 0: printf("Student failed\n"); break;
case 1: printf("Student obtained ordinary\n"); break;
case 2: printf("Student obtained third\n"); break;
case 3: printf("Student obtained two two\n"); break;
case 4: printf("Student obtained two one\n"); break;
case 5: printf("Student obtained first\n"); break;
}
}
Plain text version to compile.
This is a fairly trivial example. The point to notice is that the numbers used to represent the grades do not (and, indeed, cannot) have any direct meaning in terms of those grades, other than expressing their ordering. It is only by finding the action (printf) corresponding to each in the case statement that some meaning can be inferred.
#include < stdio.h>
void main()
{
enum DegClass {Fail,Ordinary,Third,TwoTwo,TwoOne,First};
int Mark;
enum DegClass Grade;
char MedCertificate;
scanf("%d",&Mark); /* Must be in range 0..100 */
if (Mark<45) Grade = Fail; else
if (Mark<50) Grade = Ordinary; else
if (Mark<55) Grade = Third; else
if (Mark<65) Grade = TwoTwo; else
if (Mark<80) Grade = TwoOne; else
Grade = First;
if((MedCertificate=getchar())=='y'&&Grade
Plain text version to compile.
The two examples are equivalent in their effect, but the second is more
appropriate to the problem being considered.The use of meaningful names
makes the second example much easier to read and to correct. The notion of
ordering should not be confused with that of absolute arithmetic.
Next - Making a typedef.