Introduction
When programming in C++ or C, data type names can sometimes become very long, such as unsigned long long int. Additionally, there are times when you want to distinguish the “meaning” of variables within the program, even if they share the same data type (e.g., an int storing “Age” vs. an int storing “ID”).
In such cases, the keyword typedef (short for type definition) is very convenient. Using typedef, you can assign a descriptive alias to an existing data type that fits the context of your program.
In this article, I will explain the basic usage of typedef and how it improves code readability.
Usage of typedef
typedef uses the following syntax to give a new name to an existing data type.
typedef existing_data_type new_type_name;
Sample Code
This code assigns the new name Population to the unsigned long data type and declares variables using this new type name.
#include <iostream>
// --- 1. Define a new type name with typedef ---
// Give the alias "Population" to the "unsigned long" data type
typedef unsigned long Population;
int main() {
// --- 2. Declare variables using the new type name ---
// This has the exact same meaning as writing "unsigned long tokyo;"
Population tokyo;
Population osaka;
tokyo = 14000000;
osaka = 8800000;
std::cout << "Population of Tokyo: " << tokyo << std::endl;
std::cout << "Population of Osaka: " << osaka << std::endl;
return 0;
}
Code Explanation
typedef unsigned long Population;
With this single line, the compiler recognizes the name Population as exactly the same thing as unsigned long. Population is simply an alias for unsigned long.
Population tokyo;
We declare a variable using the new type name Population defined by typedef. To the compiler, this is equivalent to writing unsigned long tokyo;.
Benefits of Using typedef
- Improved Code Readability: Writing
Population population;makes the intent—”this variable is for storing population”—much clearer than writingunsigned long population;. - Improved Portability: If you need to handle population using
unsigned long longin the future due to porting to a different environment, you only need to change that singletypedefline. - Simplification of Complex Types: It can replace complex type declarations, such as
structor function pointers, with a single, easy-to-understand name.
The “using” Keyword in C++11 and Later
In C++11 and later, an alias declaration using using was introduced for the same purpose, but with a more intuitive syntax and higher functionality.
// Same meaning as typedef
using Population = unsigned long;
In modern C++ code, using tends to be preferred over typedef.
Summary
In this article, I explained how to use typedef to give descriptive aliases to existing data types.
- Defined using the syntax:
typedef existing_type new_type_name;. - It has the effect of improving code readability and maintainability.
typedef is an important tool not just for saving typing effort, but for clarifying the “meaning” of the program.
