Professional Documents
Culture Documents
enumerators
{ 0, 1, 2, 3, 4, 5, 6}
– The value of enumerators are constant integers.
– By default, the first one is given the value 0 and each
succeeding one has the next integer value.
– Enumerators can be considered as programmer-
specified constants.
7.1 Enumeration Types (2)
/* specification of enumeration type */
enum day { sun, mon, tue, wed, thu, fri, sat };
/* to declare variables of type enum day */
enum day d1, d2;
/* to assign a value sun to d1 */
d1 = sun;
/* to assign a value wed+1 to d2 */
d2 = wed + 1;
printf("The value of d1 = %d", d1); /* 0 is printed */
printf("The value of d2 = %d", d2); /* 4 is printed */
– The variables d1 and d2 are declared as a type
enum day.
– The variables d1 and d2 can have as their values
only the enumerators in the set.
7.1 Enumeration Types (3)
variables of
type specifier
this type
day find_next_day(day d)
{
day next_day;
switch (d) {
case sun; next_day = mon; break;
case mon; next_day = tue; break;
case tue; next_day = wed; break;
case wed; next_day = thu; break;
case thu; next_day = fri; break;
case fri; next_day = sat; break;
case sat; next_day = sun; break;
}
return next_day;
}
4.3 An Example: The Game of Paper, Rock, Scissors
p_r_s selection_by_machine(void);
p_r_s selection_by_player(void);
/* 2) In file main.c: */
#include "p_r_s.h"
int main(void)
{
int win_cnt = 0, lose_cnt = 0, tie_cnt = 0;
outcome result;
p_r_s player_choice, machine_choice;
#include "p_r_s.h"
p_r_s selection_by_machine(void)
{
return ( (p_r_s) (rand() % 3) );
}
p_r_s selection_by_player(void)
{
char c;
p_r_s player_choice;
#include "p_r_s.h"
if (player_choice == machine_choice)
return tie;
switch (player_choice)
{
case paper: /* 보 */
result = (machine_choice == rock) ? win : lose; break;
case rock: /* 바위 */
result = (machine_choice == scissors) ? win : lose; break;
case scissors: /* 가위 */
result = (machine_choice == paper) ? win : lose; break;
default:
printf("PROGRAMMER ERROR: Unexpected choice!\n\n"); exit(1);
}
return result;
}
/* 5) In file report.c: */
#include "p_r_s.h"
#include "p_r_s.h"