In C++, the keyword typedef is used to create aliases for existing data types, to facilitate code readability and maintenance.
They are especially suitable for simplifying the declaration of complex types (such as those involving heavy use of pointers).
Besides improving readability, it also facilitates portability between platforms (for example, by creating aliases for variable types with different names)
Basic Syntax
The basic syntax of typedef is as follows
typedef data_type alias_name;
For example,
typedef unsigned long ulong;
In this example,
ulongbecomes an alias forunsigned long, allowing the use ofulonginstead of writingunsigned longevery time.
Common Uses of typedef
Aliases for Simple Data Types
The most basic use of typedef is to create aliases for simple data types, such as int, char, float, etc.
typedef int entero;
typedef float real;
typedef char caracter;
Now, you can use entero, real, and caracter instead of int, float, and char, respectively.
This might seem like a “weird” example. But, for instance, it’s common for many libraries to define their own types like i32, f64, and similar, to facilitate portability.
Aliases for Pointers
typedef is especially useful for creating aliases for pointers, which can significantly improve readability.
typedef int* intPtr;
In this example, intPtr is an alias for int*.
Aliases for Structured Types
When working with structures (structs), typedef can greatly simplify their use and declarations.
typedef struct {
int x;
int y;
} Point;
Point p1;
p1.x = 10;
p1.y = 20;
In this example,
Pointis an alias for the anonymous structure- It allows using
Pointdirectly to declare structure-type variables
Practical Examples
For more complex data types, such as function pointers or arrays, typedef can make declarations much more manageable.
Function Pointers
The declaration of function pointers can be particularly confusing. typedef can simplify this task.
typedef void (*CallbackFunction)(int, int);
void myFunction(int a, int b) {
std::cout << "a: " << a << ", b: " << b << std::endl;
}
int main() {
CallbackFunction callback = myFunction;
callback(5, 10);
return 0;
}
In this example,
CallbackFunctionis an alias for a pointer to a function that takes twoints and returnsvoid.
Arrays and Matrices
For arrays and matrices, typedef can also help make declarations clearer.
typedef int Matrix3i[3][3];
Matrix3i matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
In this example, Matrix3i is an alias for a two-dimensional array (a matrix) of integers sized 3x3.
