UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

3.2.  Defining type aliases with typedef

C allows to define synonyms for the data types by using the typedef operator and the following syntax:

typedef already_defined_data_type synonym

For example, the following line defines integer as a synonym of int.

typedef int integer

This operator is used frequently to abbreviate the names of the data structures. The name of a structured data type is struct followed by its name. With typedef a more compact synonym can be defined as shown in the following example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#define SIZE_FIRST 100
#define SIZE_LAST 200
#define NUM_CONTACTS 100

/* Structure definition */
struct contact_information 
{
    char firstname[SIZE_FIRST];
    char lastname[SIZE_LAST];
    unsigned int homephone;
    unsigned int mobilephone;
};
/* Variable declaration */
struct contact_information person2;
/* Definition of the synonym */
typedef struct contact_information contact_info;
/* Declaration using the synonym */
contact_info person1, contacts[NUM_CONTACTS];

Line 16 defines contact_info as synonym of the structure. Line 18 uses this synonym to declare two more variables of this type. The definition of a structure and a synonym can be combined into a single block as shown in the following example, even though we recommend the first alternative, for readability reasons:

/* Structure and synonym definition */
typedef struct contact_information 
{
    char firstname[SIZE_FIRST];
    char lastname[SIZE_LAST];
    unsigned int homephone;
    unsigned int mobilephone;
} contact_info;