typedef
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: frey@cs.umbc.edu
**
** Example using typedef
*********************************************/
#include
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;