UMBC CS 201, Fall 06
Fall '06

CSEE | 201 | 201 F'06 | lectures | news | help


The ANSI C typedef facility allows us to give data types a more convenient name. It is commonly used to help programmers relate an object they are working with to a name that makes more sense to them than the datatype's real name.

When using typedef , you aren't really defining a new datatype, as the name might imply, but just giving a name to some known type. For example, if you were writing a program about x- and y-cooridnates (like the points and lines from the previous lecture) you might consider this typedef

typedef int COORDINATE; This declaration makes COORDINATE an alias for int. Note that our naming convention is to use UPPERCASE for typedefs, just as with #defines. Once COORDINATE is typedefed, we can declare variables of that type, as in : /********************************************* ** File: typedef.c ** Author D. Frey ** Date: 1/20/00 ** Section: 202 ** EMail: ** ** Example using typedef *********************************************/ #include <stdio.h> typedef int COORDINATE; int main() { COORDINATE x, y; printf ("Please enter the x-coordinate: "); scanf ("%d", &x); printf ("Please enter the y-coordinate: "); scanf ("%d", &y); /* more code here */ }

Why would I do this?

The reason for using typedef in this way is maintainability. By using COORDINATE (instead of int), it's much clearer what the variables x and y represent. Also, if you later decide that you want to use floats instead of ints for the coordinates, simply change the typedef to typedef float COORDINATE; Note -- some other changes will still need to be made, but there will be many fewer than without the typedef. Code such as the printf() above that "knows" that COORDINATE is really an int will have to change to "know" that COORDINATE is now really a float.

typedefs and structures

Although typedefs are used as described above, typedef is more commonly used by programmers to make aliases for structures. Recall struct point from last time. struct point { int x; int y; }; We can make an alias for struct point using typedef typedef struct point POINT; More commonly, the structure is typdefed when it is defined: typedef struct point { int x; int y; } POINT; In either case we can now declare struct point variables using POINT point;

CSEE | 201 | 201 F'06 | lectures | news | help

Tuesday, 22-Aug-2006 07:14:10 EDT