User-Specified Data Types ------------------------- Sometimes it would be nice to be able to define your own data types. Let's say that you wanted a data type for True and False. You can use enumerated data types to make this definition. Enumerated Data Types --------------------- The format for an enumerated data type is: enum name {item1, item2, ... , itemn}; The example given above could be represented like this: enum flag {true, false}; Now when you access flag, you can directly test for "true" or "false" like this: if (flag === true) or if (flag != false) In this case, true and false, are not variables. They are values! Let us try another example: enum days {sun, mon, tue, wed, thu, fri, sat}; A sample C fragment using these looks like this: switch (days) { case sun: case tue: case thu: printf("It is a ride day!\n"); break; case mon: case wed: case fri: case sat: printf("It is a run day!\n"); break; default: break; } When you print the value back, the integer value is shown. The list of days above corresponds to 0, 1, 2, 3, 4, 5, 6. If the commands day = tue; printf("%d\n", day); were executed. The value of 2 would come back since tue corresponds to 2. The typedef Statement --------------------- The typedef command allows you to rename data types and create new data types. For example: typedef float REAL; This adds a new data type called REAL that is identical to the float data type. So now in a program, you could declare vaariables of type REAL. REAL a, b; int c,d; You could also define arrays like this: typedef int ARRAY[20]; ARRAY h; The variable h is an array of type int size 20. A practical example in graphics would be to define a 3D point or a 2D point. This may be done like this: typedef short POINT3D[3]; typedef short POINT2D[2]; POINT3D pt1, pt2; POINT2D p, q, r; The #define Statement --------------------- This was covered previously for simple cases of redefining. Here I will present some more complicated #define uses. If you wanted to define a simple value this is done like the usual: #define value 3.1455555 If you wanted to make a simple expression such as square(x) which takes x and multiplies by itself, do this: #define square(x) (x) * (x) This may be used like: square(10) This value is 100. One more example: #define average(a,b,c) ((a) + (b) + (c)) / 3.0 To use it, try this program: #define avg(a,b,c) ((a) + (b) + (c)) / 3.0 main() { int a = 10, b = 7, c = 11; printf("avg = %f\n",avg(a,b,c)); } The output is: avg = 9.333333