5.8.3 typedef Statements

typedef existing data type alias; typedef unsigned long ulong; ulong file_length;
(a)(b)(c)
typedef syntax and example. The typedef keyword creates a new, usually shorter, name or alias for an existing data type.
  1. The syntax or general pattern of a typedef statement is straightforward. The "alias" consists of exactly one word. Therefore, all text between the keyword and the alias, regardless of the number of words or lines, forms the "existing data type."
  2. Suppose that a program frequently uses the data type unsigned long. Programmers can create a new shorthand name or alias with a typedef statement or with a macro: #define unsigned long ulong. The compiler component processes typedef statements, which are fully type-checked and the preferred method. The preprocessor implements macros by replacing one string with another without any error-checking.
  3. The alias is a new, shorter type specifier programmers use to define variables or function return types.

C programmers use typedef statements to achieve a modest code-size reduction.

C C++
struct Foo my_foo;
Foo my_foo;
union Bar my_bar;
Bar my_bar;
C vs. C++. Whenever a programmer defines a structure or union variable, C requires the corresponding keyword as part of the type specifier, but C++ does not.

A more common example, demonstrated by the C FILE type, is hiding the details of library code from application programs.

typedef struct { . . . } FILE;
FILE* fp = fopen("name", "w");
fprintf(fp, "x = %f\n", x);
(a)(b)(c)
The stdio.h FILE type: A data hiding example. The structure is the "existing data type." It has fields saving the file's name, file descriptor (an integer assigned by the operating system), location in the file system, the current read/write position in the file, etc. The application program uses the FILE type without "knowing" or directly accessing the data saved in the structure.
  1. The FILE declaration is the heart of the stdio.h header file.
  2. A library function, fopen, opens a file (for writing in this example), filling in and returning a structure object.
  3. The fprintf function, like the others in stdio.h uses the data saved in the structure object to complete its task.
The application does not access the file information in the structure object at any time.