TypeDef

Typedef in C++ is a keyword used to create aliases or alternative names for existing data types. It's a way to simplify complex type declarations and make code more readable.

  1. Basic Syntax:

    typedef existing_type new_type_name;
  2. Simple Example:

    typedef unsigned long ulong;
    ulong myNumber = 1000000UL;
  3. Array Typedef:

    typedef int IntArray[5];
    IntArray myArray = {1, 2, 3, 4, 5};
  4. Pointer Typedef:

    typedef int* IntPtr;
    IntPtr ptr = new int(10);
  5. Function Pointer Typedef:

    typedef int (*MathFunc)(int, int);
    int add(int a, int b) { return a + b; }
    MathFunc operation = add;
  6. Struct Typedef:

    typedef struct {
        int x;
        int y;
    } Point;
    
    Point p = {10, 20};
  7. Complex Types:

    typedef std::vector<std::pair<std::string, int>> NameScorePairs;
    NameScorePairs scores;
  8. Template Typedef (C++11 and later):

    template<typename T>
    using Vec = std::vector<T>;
    
    Vec<int> numbers = {1, 2, 3, 4, 5};
  9. Improving Readability:

    typedef std::unique_ptr<MyClass> MyClassPtr;
    MyClassPtr ptr = std::make_unique<MyClass>();
  10. Portability:

    typedef long long int64;  // Ensures 64-bit integer across platforms

Example:

Run it here.

Key points about typedef:

  • It doesn't create a new type; it just introduces a new name for an existing type.

  • It can make complex declarations more readable.

  • It's often used to create platform-independent type definitions.

  • In modern C++ (C++11 and later), the using keyword can be used similarly to typedef and is more flexible, especially with templates.

Last updated