Language: EN

cpp-typedef

How to use typedef in C++

In C++, the typedef keyword is used to create aliases for existing data types, to enhance code readability and maintenance.

They are particularly suitable for simplifying the declaration of complex types (such as those involving heavy use of pointers).

Additionally, they improve readability and 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 for unsigned long, allowing the use of ulong instead of writing unsigned long every 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, entero, real, and caracter 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 like i32, f64, and things like that, to facilitate portability.

Aliases for Pointers

typedef is especially useful for creating aliases for pointers, which can significantly enhance 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 using 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 two int and returns void

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 of 3x3.