TypeDefs
TypeDefs

typedef is a facility provided by C which allows us to rename a datatype to a more convenient, or intuitive, name. Using typedef statements also simplifies mass changes later on if they are needed.

Let's say we have a program with computes grades for a student. We might consider using the following typedef:

typedef int GRADE; If we then write a program which uses this typedef: /* NOTE: I didn't compile this... It may or may not be syntactically * correct. */ int main() { GRADE midterm, final, proj1, proj2; GRADE courseAveerage; printf("Please enter the grades you recieved on your Midterm, Final,\n Project 1 and Project2 separated by spaces (ie. 90 78 98 30):\n"); scanf("%d %d %d %d", &midterm, &final, &proj1, &proj2); courseAverage = (midterm * 0.25) + (final * 0.35) + (proj1 * 0.2) + (proj2 * 0.2); printf("\nYour average in this course is %d", courseAverage); return(0); } Later after you have debugged and tested the program, you decide that truncating the values into ints is not what you had in mind for the student's grade and you want to change the values in the function to deal in floats versus ints.

First you would change the typedef statement to read:

typedef float GRADE; Then you would change the printf and scanf statements in the program from "%d" to "%f". This may not seem like a significant advantage in this example, but imagine you were one of 50 programmers working on a large project for a major corporation. Your portion of the project handles only computational functions (you don't get anything from the user or print anything). Now one of the big bosses decided that the current program is not precise enough and wants that changed. If you are using typedef statements... you may have nothing to change in your code. See the advantage now?


Main Page
Last Modified 24 October 2000