
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Typedef Declarations in C++
In C++, typedef is a keyword that is used to create a new name for an existing data type. This helps the users to modify the code according to their preference, making it more readable, friendly, and manageable.
Syntax
Here is the following basic syntax of typedef in C++;
typedef existing_type new_name;
Here, existing_type is the original data type given in the C++ standard (e.g., int, float, double, etc.)
new_name is the new name assigned to that type.
Example
Here is the following simple example showcasing the use of typedef in C++:
#include <iostream> using namespace std; // Defining a new name for the int data type to hey_integer typedef int hey_integer; int main() { hey_integer num = 10; cout << "The value of num is: " << num << endl; return 0; }
Output
The value of num is: 10
Here, we have created the custom name hey_integer for the int type using typedef and declared an integer variable using it.
Advantages of typedef
1) This can be used to replace complex or long type declarations with simple names, thus improving the code readability.
Example:
typedef unsigned long long ULL;
2) This also helps in simplifying complex data types, especially when working with pointers, function pointers, structures, and arrays etc.
Example: Instead of declaring pointers like this
int* a; int* b;
You can use typedef to simplify while working with multiple pointers.
typedef int* IntPtr; IntPtr a, b;
3) It makes the code maintenance easier, like if it is required to change the base type later, then you can change it in only one place at the typedef, no need to explicitly change everywhere.
Alternative Approach
There also exists an alternative approach for typedef, that's 'using' keyword introduced in C++11.
This also works the same as typedef, but it is cleaner and more powerful, especially when working with templates. Thus, it provides better template support and cleaner code.
Example
using IntPtr = int*; IntPtr a, b;