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.
Basic Syntax:
typedef existing_type new_type_name;Simple Example:
typedef unsigned long ulong; ulong myNumber = 1000000UL;Array Typedef:
typedef int IntArray[5]; IntArray myArray = {1, 2, 3, 4, 5};Pointer Typedef:
typedef int* IntPtr; IntPtr ptr = new int(10);Function Pointer Typedef:
typedef int (*MathFunc)(int, int); int add(int a, int b) { return a + b; } MathFunc operation = add;Struct Typedef:
typedef struct { int x; int y; } Point; Point p = {10, 20};Complex Types:
typedef std::vector<std::pair<std::string, int>> NameScorePairs; NameScorePairs scores;Template Typedef (C++11 and later):
template<typename T> using Vec = std::vector<T>; Vec<int> numbers = {1, 2, 3, 4, 5};Improving Readability:
typedef std::unique_ptr<MyClass> MyClassPtr; MyClassPtr ptr = std::make_unique<MyClass>();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
usingkeyword can be used similarly to typedef and is more flexible, especially with templates.
Last updated