enum color { RED, YELLOW, GREEN }
enum color c1;
...
c1 = GREEN; /* same as c1= 2; */
if (c1 != RED)
...
By default, values start at zero, so here RED has the value 0, YELLOW 1, and GREEN 2.
Explicit values may be specified. Here, JAN has value 0, FEB 2, etc. :
enum months { JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };
As with the struct keyword, we can use enum with typedef
typedef enum __color { RED, YELLOW, GREEN } color
color c1;
...
c1 = GREEN; /* same as c1= 2; */
We can compare enumeration values
if(mon1 < DEC)
...
We cannot use the same enumeration constant with more than one enumeration.
int rand(void);
By default rand is seeded with a value of 1.
We can call srand to set a new seed for a sequence or random intergers.
int srand(unsigned int seed);
If we want to see a unique sequence of random numbers each time our program runs, then we can seed srand with a number that varies with the time of day, such as time in time.h.
srand(time(NULL));
...
int i = rand();
char (* pStrFunc )(const char *);
...
pStrFunc = &strdup;
This assignment (without &) is also valid:
pStrFunc = strdup;
Function pointers can be: assigned, stored in arrays, and passed as arguments
You will never need to call malloc or free with a function pointer!
Now, let's compare this to another version that uses function poiters.
Here, we can decide at runtime how pointers are called:
void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *));
qsort sorts the array with nmemb elements of size size. The base argument points to the start of the array.
What is the type of the third argument, compar?
int(*compar)(const void *, const void *));
Exercise: Modify Example 4 so that dates are sorted by month and date, not just month.
SOLUTION:
ex5_str_soln.c
Text
typedef char (* pStrFunc_t )(const char *); /* define the type pStrFunc_t */
pStrFunc_t pStrFunc;
...
pStrFunc = &strdup;