C enum type
Description
Enumerations are integer types defined in a program.
Syntax
The definition of an enumeration begins with the keyword enum, possibly followed by an identifier for the enumeration, and contains a list of the type's possible values, with a name for each value:
enum [identifier] { enumerator-list };
Example - Define and use enum
#include <stdio.h>
// w w w . j av a2 s . c om
enum computer {keyboard, CPU, screen, printer, mouse};
int main(void){
enum computer comp;
comp = CPU;
printf("%d", comp);
return 0;
}
Example - Reference enum value by int
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/*from w w w .j a va2s. c o m*/
enum transport {car, train, airplane, bus} tp;
int main(void)
{
printf("Press a key to select transport: ");
getch(); /* read and discard character */
tp = rand() % 4;
switch(tp) {
case car: printf("car");
break;
case train: printf("train");
break;
case airplane: printf("airplane");
break;
case bus: printf("bus");
}
return 0;
}
Example - Map enum to string array
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/* w w w.j av a 2s. c o m*/
enum transport {car, train, airplane, bus} tp;
char trans[][20] = {
"car", "train", "airplane", "bus"
};
int main(void)
{
getch(); /* read and discard character */
tp = rand() % 4;
printf("%s", trans[tp]);
return 0;
}
Example - Map enum to char and output with for loop
#include <stdio.h>
//from w w w.j a v a 2 s .c o m
enum spectrum { red, orange, yellow} colour;
char *rainbow[] = { "red", "orange", "yellow" };
int main() {
for ( colour = red; colour <= yellow; colour++ ) {
printf ( "%s ", rainbow[colour]);
}
printf ( "\n" );
}