cpp-typedef

How to use typedef in C++

  • 3 min

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;
Copied!

For example,

typedef unsigned long ulong;
Copied!

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;
Copied!

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;
Copied!

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;
Copied!

In this example,

  • Point is an alias for the anonymous structure
  • It allows using Point directly 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.