Enums
CSCI 112: Programming in C
Enums CSCI 112: Programming in C Fitting C data types to the real - - PowerPoint PPT Presentation
Enums CSCI 112: Programming in C Fitting C data types to the real world So far, weve seen int , double , float and char For a lot of real world data, these fit well! What sorts of things would be difficult to represent with these
CSCI 112: Programming in C
category—for example NORTH, SOUTH, EAST and WEST
name
enum directions { NORTH, // 0 SOUTH, // 1 EAST, // 2 WEST // 3 }; enum directions my_direction = WEST;
the value as an int
enum directions { NORTH, SOUTH, EAST, WEST }; enum directions my_direction = WEST; int x = (my_direction== 3); // This expression is TRUE (x is 1)
enum identifier
enum
“my_direction” is of type the enumerated type “directions”
the enum you declared
through 3 (NORTH through SOUTH) are specified
we can define a new C data type!
typedef enum { NORTH, SOUTH, EAST, WEST } directions_t; directions_t my_direction = WEST;
typedef int fred_t; fred_t x = 345;
familiar operations with them
typedef enum { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } day_t;
day_t day_of_week = Tuesday; switch( day_of_week ) { case Monday: // ugh, monday? really? break; case Tuesday: // meh break; ... }
arithmetic
direction_t direction = EAST; direction_t toLeft = --direction; // Returns NORTH direction_t toRight = ++direction; // Returns SOUTH