Hi there,
Is this allowed in ANSI C? My compiler says it's okay. If so, what is the
point of using enum instead of #define?
typedef enum
{
ONE = 1,
TWO = 2,
THREE = 3
} NUMBERS;
int main()
{
NUMBERS num = 5;
return 0;
}
NUMBERS is a type which can have the values of all enumeration constants
you specified in your enum (and all the values in between).
An enumeration does _not_ provide a means to specify a set of values
which variables of the type can take on -- which probably is the
functionality you hoped for.
What you _can_ do, however, is using enumeration constants like symbolic
constants without having to care about the value. If you want to have,
for example, a means to distinguish between different cases but do not
care about the numbers behind the constants, you just use an enumeration
enum dc { firstcase, secondcase, thirdcase, fourthcase };
If you add a fifth case, you do not have to look for a new number to
assign to it but just use it.
Think of it as a convenient way of obtaining valid constants no two
of which are equal (if you do not wish it).
The discussion you find under
http://groups.google.com/groups?th=430152de91554ce3
may give you some additional ideas.
I like using C99 designated initializers along with enumerations,
e.g.
.....
/* Usage: Enter new sorting algorithm in list of algos after creating
** an enum entry.
*/
/* Enumeration of possible sorting algos */
typedef enum sortingalgos {START=-1,
selection,
insertion,
bubble,
shell,
quick,
LAST
} Counter;
/* Function pointer type for sorting algos */
typedef int (* MySortProcPtr) (int *, size_t);
/* Structure containing all algo information */
typedef struct {
char algochar; // I/O identifier
char *algoname; // Name to be printed
MySortProcPtr algofunc; // Function pointer
} SortingInfo;
/* Actual list; global for convenience */
static SortingInfo MyInfo[] = {
[selection] = {'s', "selection sort" , selectionsort},
[insertion] = {'i', "insertion sort" , insertionsort},
[bubble] = {'b', "bubble sort" , bubblesort},
[shell] = {'S', "Shell sort" , shellsort},
[quick] = {'q', "quick sort"
" (recursive,"
" middle of three,"
" insertion sort)" , quicksort}
};
.....
You loop with a Counter variable from START+1 to <END to search
for the identifiers, print the name, call the function but still
are able to handle exceptions by checking for the corresponding
enumeration constant. Using the designated initializer with the
constant makes sure that you never ever check for the wrong array
index...
Cheers
Michael