📜  typedef - C++ (1)

📅  最后修改于: 2023-12-03 15:35:23.619000             🧑  作者: Mango

Typedef in C++

typedef is a keyword in C++ that is used to give data types a new name and make it easier to read and understand the code. It is essentially a shortcut for declaring a new type that is identical to an existing type. Let's explore more about typedef and its usage.

Syntax

The syntax to declare a typedef is:

typedef <existing_data_type> <new_name>;

For example, to create a new name myInt for an int, we can use:

typedef int myInt;

Now, wherever we need to use int, we can simply use myInt instead.

Usage

Let's take some examples to understand the usage of typedef better.

Example 1
typedef unsigned int uint;

Here, we have created a new name uint for unsigned int. Now, we can use uint in place of unsigned int.

Example 2
typedef struct {
  int x;
  int y;
} Point;

Here, we have created a new name Point for a structure that has two members x and y. Now, we can declare a variable of type Point instead of declaring a structure every time.

Point p1;
Example 3
typedef int (*pointerToFunction)(int, int);

Here, we have created a new name pointerToFunction for a pointer to a function that takes two int arguments and returns an int. Now, we can declare a pointer variable of type pointerToFunction instead of declaring a function pointer every time.

int add(int a, int b) {
  return a + b;
}

pointerToFunction ptr = &add;
Conclusion

In conclusion, typedef is a useful keyword in C++ that allows us to give new names to existing data types, structures, and function pointers. It helps in making the code more readable and understandable.