Using typedef

The typedef operator lets you rename a data type, like creating an alias. One of its main uses is to increase the portability of C applications: a common header file can include aliases to specific data types for different computers. By changing the particulars of the header file, the application should work on another system.

As an example, before the C99 standard supported the boolean type, you could have used typedef to create it yourself (which would store 0 or 1):

typedef int boolean;
boolean correct;

The typedef operator can be used nicely with structures to simplify your declarations:

structure students {
   char name[30];
   gpa float;
};

The formal way to create a variable of this structure's type is

struct students timmy;

By using typedef, you can create an alias:

typedef struct students student_type;

Now, to declare a variable of this structure's type, just use

student_type timmy;

The typedef line of code makes the word student_type act as shorthand for struct students.

Using typedef like this can make your code easier to type and easier to read. It will be used in our next example, read_weather, which will retrieve all the data from the binary weather.dat file and display it.

To use typedef

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 13.2).

/* read_weather.c - Script 13.2 */
#include <stdio.h>

Script 13.2. The typedef operator can help shorten how you refer to structures. This application uses those structures to read data from a binary file.


3.
Set the file path and name as a C preprocessor macro:

#define THEFILE
 "/Users/larry/Desktop/weather.dat"

or

#define THEFILE "C:\Documents and
 Settings\Larry Ullman\Desktop\
 weather.dat"

This should point to the exact same file we used in weather_structure.c (Script 13.1).

4.
Begin the main function:

int main (void) {

5.
Define the structure:

struct weather_record {
     char date[11];
     int high;
     int low;
};

The structure also matches the same structure defined in the previous example.

6.
Use typedef to redefine the structure type, then create a structure variables:

typedef struct weather_record wr;
wr day;

The first line makes an alias so that wr (short for weather_record) stands for struct weather_record. Then wr is used to create a day variable of type struct weather_record.

7.
Create a file pointer and open the file for binary reading:

FILE *fp;
fp = fopen(THEFILE, "rb");
if (fp != NULL) {

8.
Read in the contents of the data file in a loop:

while (fread (&day, sizeof(wr), 1,
 fp)) {

This line says that 1 block of sizeof(wr) bytes should be read from the file and assigned to day. Without using the typedef operator, the second parameter would have to be formally written out as sizeof(struct weather_record).

As long as this condition is true—that a block could be read from the binary file—the contents of the loop will be executed.

9.
Print each record:

printf ("Date: %s
High: %d
Low:
 %d

", day.date, day.high,
 day.low);

A simple print statement is used to send each record to the standard output. To access the individual members (which are stored in the day structure), use the day.membername syntax.

10.
Complete the while loop:

}

11.
Complete the fp conditional:

} else {
    printf ("The file could not
 be opened.
");
    return 1;
}

12.
Close the file:

if (fclose(fp) != 0) {
    printf ("The file could not
 be closed.
");
}

13.
Complete the main function:

    getchar();
    return 0;
}

14.
Save the file as read_weather.c, compile, and debug as necessary.

15.
Run the application (Figure 13.6).

Figure 13.6. This application uses structures to parse individual elements out of a binary file.


✓ Tips

  • Although you should place your typedef statements toward the top of your code, the only requirement is that they are defined before they are used.

  • When you have a series of applications all of which use the same data file and structure definition (like weather_structure and read_weather), you could benefit from using an external library file. Place the #define macro and the structure definition is a plain-text file called defs.h and then include this in your other C files.

  • Overusing typedef or using it in ways that's not clear can lead to confusing code. Each alias you make should be fairly obvious and useful.


Enumerated Types

Although the enumerated type is not the most popular or useful data type in C, it does have its place and being familiar with it is worth your while. An enumerated type is a special variable type you define that limits the possible values a variable can have. For example, a weekday variable can have only one of seven possible values (Sunday, Monday, Tuesday, etc.) or a month variable can be only one of 12 possible values.

To define an enumerated type, use the enum keyword:

enum type_name {possible values};
enum weekdays {Sunday, Monday, Tuesday, Wednesday, Thursday,
 Friday, Saturday};

Once you've defined the type itself, you can create a variable of that type:

enum weekdays appt_day;

Now the appt_day can only be assigned one of those seven values:

appt_day = Tuesday;

Notice that quotation marks are not being used in either the enumerated type definition or in assigning the specific variable a value. This is because the different values become named constants in C. Enumerated types are actually of type int. C will, behind the scenes, assign the numbers 0, 1, etc. to the possible values.

Because the enumerated values are actually integers, you can specify their values:

enum months {January = 1, February = 2, ...};

or just

enum months {January = 1, February, March, ...};

Another nice feature of enumerated types is that they can be used in switch statements, unlike strings.

Essentially the enumerated type does two things for you:

  • It allows you to use words instead of numbers to represent values.

  • It forces a variable to have an appropriate value.

Whether or not you use enumerated types is mostly a matter of preference. It won't hurt to never use them, but you may appreciate what they offer. Some programmers use enumerated types more like comments, as a way of documenting how a variable is supposed to behave.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset