Programming: Typedef

Now, what if you wanted to designate an existing data type under a different name? Suppose you wanted to give aliases to the char data type, to separate instances where you are using it to represent an alphanumeric character and other instances where you are using it as a number. When we use aliases, it is easier to understand why a variable was declared to be a specific type. This is especially beneficial when the original type name does not provide enough information. Typedef offers the mechanism to rename data types within our code.

Typedef, which is short for type definition, allows the user to give an alternate name to a preexisting data type. Typically, in C, typedef is paired with enums and structs, which we will discuss later. Let’s take the previous example with the traffic light colors. Suppose we made the following declaration:

typedef enum { RED, YELLOW, GREEN } traffic_light_t;

We can create a new variable as follows:

traffic_light_t myColor;

This code is functionally equivalent to the example in the previous section. You can replace traffic_light_t with enum { RED, YELLOW, GREEN }, and the code would function precisely the same. In a sense, that is what typedef does: it is a substitution to an existing enumerated data type, just under a comprehensible name. These types are extremely helpful in developing functions with clean interfaces that are easy to read and understand. For example, you can write a code like this:

traffic_light_t changeLight(traffic_light_t inputColor);

Without typedef and enum, the code would have looked like this:

unsigned int changeLight(unsigned int inputColor);

The function changeLight is essentially accepting an integer as input that represents a color and returns another integer that again represents a color. Typedef and enum do not change the essence of the code; they only make code easier to read and understand. Readability is critical because it results in fewer errors in the code and makes the code easier to test and maintain.

(Learn more: https://www.studytonight.com/c/typedef.php

To learn more about macros, enum, and typedef import the following project into CCS:

https://github.com/VT-Introduction-to-Embedded-systems/macro_enum_typedef