2. 2
Enumeration Types
Example
#include <stdio.h>
void main(void)
{
int color ;
for( color = 0 ; color <= 2 ; color++ ) {
switch( color ) {
case 0 : printf( “Yellown” ) ; break ;
case 1 : printf( “Redn” ) ; break ;
case 2 : printf( “Bluen” ) ; break ;
}
}
}
3. 3
Enumeration Types
Example
#include <stdio.h>
#define YELLOW 0
#define RED 1
#define BLUE 2
void main(void)
{
int color ;
for( color = YELLOW ; color <= BLUE ; color++ ) {
switch( color ) {
case YELLOW : printf( “Yellown” ) ; break ;
case RED : printf( “Redn” ) ; break ;
case BLUE : printf( “Bluen” ) ; break ;
}
}
}
4. 4
Enumeration Types
Example
#include <stdio.h>
#define YELLOW 0
#define RED 1
#define BLUE 2
#define Color int
void main(void)
{
Color color ;
for( color = YELLOW ; color <= BLUE ; color++ ) {
switch( color ) {
case YELLOW : printf( “Yellown” ) ; break ;
case RED : printf( “Redn” ) ; break ;
case BLUE : printf( “Bluen” ) ; break ;
}
}
}
5. 5
Enumeration Types
enumeration Types
– Variables of enum type can be used in indexing expressions
and as operands of all arithmetic and relational operators
[Ex]
enum day { sun, mon, tue, wed, thu, fri, sat };
enum day d1, d2;
d1 = fri;
tag name
By default, the first element ‘sun’ is associated with 0.
The next element, mon, is associated with 1.
…
Define variables d1, d2 as type of enum ‘day’,
Assign a value of fri to d1
6. 6
Enumeration Types
Example
#include <stdio.h>
enum color_type {Yellow, Red, Blue} ;
void main(void) {
enum color_type color ;
for( color = Yellow ; color <= Blue ; color++ ) {
switch( color ) {
case Yellow : printf( “Yellown” ) ; break ;
case Red : printf( “Redn” ) ; break ;
case Blue : printf( “Bluen” ) ; break ;
}
}
}
7. 7
typedef
Example
#include <stdio.h>
enum color_type {Yellow, Red, Blue} ;
typedef enum color_type Color ;
void main(void) {
Color color ;
for( color = Yellow ; color <= Blue ; color++ ) {
switch( color ) {
case Yellow : printf( “Yellown” ) ; break ;
case Red : printf( “Redn” ) ; break ;
case Blue : printf( “Bluen” ) ; break ;
}
} }
8. 8
typedef
Example
#include <stdio.h>
typedef enum {Yellow, Red, Blue} Color ;
void main(void) {
Color color ;
for( color = Yellow ; color <= Blue ; color++ ) {
switch( color ) {
case Yellow : printf( “Yellown” ) ; break ;
case Red : printf( “Redn” ) ; break ;
case Blue : printf( “Bluen” ) ; break ;
}
}
}
10. 10
Enumeration Types
Feature of enum type
– enum types are equivalent to integer type
[Ex]
int i;
enum { CLUBS, DIAMONDS, HEARTS, SPADES } s;
i = DIAMONDS; /* i = 1 */
s = 0; /* s = CLUBS */
s++; /* s = 1 */
i = s + 2; /* i =3 */