In C++, the keyword typedef
is used to create aliases for existing data types, to facilitate readability and maintenance of the code.
They are especially suitable for simplifying the declaration of complex types (such as those involving heavy use of pointers).
In addition to improving readability, they also facilitate portability across 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,
ulong
becomes an alias forunsigned long
, allowing the use ofulong
instead of writingunsigned long
each 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 integer;
typedef float real;
typedef char character;
Now, integer
, real
, and character
can be used instead of int
, float
, and char
, respectively.
It may seem like a “strange” example, but for instance, it is common for many libraries to define their types i32, f64, and things like that, 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 usage and declarations.
typedef struct {
int x;
int y;
} Point;
Point p1;
p1.x = 10;
p1.y = 20;
In this example,
Point
is an alias for the anonymous structure- It allows the use of
Point
directly to declare structure type variables
Complex Types and typedef
For more complex data types, such as function pointers or arrays, typedef
can make declarations much more manageable.
Function Pointers
Declaring 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,
CallbackFunction
is an alias for a pointer to a function that takes twoint
and returnsvoid
Arrays and Matrices
For arrays and matrices, typedef
can also help us 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 3x3.