What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

typedef in C++: Syntax, Examples and Use Cases (with code)

  • Jan 02, 2023
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Anubhav Agarwal
typedef in C++: Syntax, Examples and Use Cases (with code)

In this article, we will learn about what is typedef in C++, its example, and why it is used. We are going to have a lot of fun while learning about this. We will understand the syntax and applications also. So let's start!

What is typedef in C++?

The typedef provides us the abstraction by hiding the actual keywords defined in C++ to the custom keywords name defined by us. This makes our code more readable and user-friendly. Also, sometimes replacing big length keywords like unsigned long long int with Ulli can make our job easy to do and as a consequence, we can focus on the code logic more. But using typedef in every program where it is not much effective is not recommended.

Here is the syntax for typedef in C++:

typedef <data_type> <alias_name> ;

 

(alias: In short, means synonym.)

How to use typedef?

Consider a game where we have one player playing and we need to measure its health which has a range for unsigned short int in C++. Let's quickly jump into our C++ code then.

#include
using namespace std;
int main(){

    unsigned short int playeronehealth;

    return 0;
}

 

Now let's use typedef in the above scenario, and see what will happen!

#include
using namespace std;
typedef unsigned short int health; // see this
int main(){

    health playeronehealth;

    return 0;
}

 

Similarly, we have the following scenarios where it will make our understanding of the code.

#include
suing namespace std;
typedef unsigned short int health; 
typedef unsigned short int health;
typedef bool win;  
int main(){

    health playeronehealth;
    health playertwohealth;
    won playerone = true;
    won playertwo = false;

    return 0;
}

 

 We can also use typedef with arrays. Suppose our player is currently carrying some weapons which we need to determine so we can declare an array using below:

#include
suing namespace std;
typedef unsigned short int health; 
typedef unsigned short int weapon;
typedef unsigned short int equipment;
typedef bool win;  
int main(){

    health playeronehealth;
    health playertwohealth;
    won playerone = true;
    won playertwo = false;
    weapon hands[2];
    equipment backpack[10];

    return 0;
}

 

Now, let's see what we can extract from typedef more to make our job convenient.

 Consider the below code where we have used for instead of float using typedef in C++:

#include
suing namespace std;
typedef float foo;  
int main(){
    foo x;
    foo y;
    foo z;

    return 0;
}

 

Suppose in the future we will want to switch the data type of our 'foo' from bool to int, then it will be very easy for you to just write int in place of bool in 3rd line of typedef instead of writing int from bool everywhere in the code which can cause error too because it might happen that you will switch the data type at the wrong place.

More Examples 

Syntax of typedef on vectors:

typedef std::vector<int> vInt;

 

Below is the C++ Program to implement typedef:

// Welcome to FavTutor
// C++ Program to implement typedef
#include <bits/stdc++.h>

using namespace std;

int main()
{
	// Now we can make more vectors by using vInt
	typedef std::vector<int> vInt;

	// vec1 is a vectorof type int
	vInt v;

	v.push_back(190);
	v.push_back(180);
	v.push_back(10);
	v.push_back(10);
	v.push_back(27);

	for (auto X : v) {
		cout << X << " ";
	}

	return 0;
}

 

Output:

190 180 10 10 27 

 

Why typedef is used in C++?

Here are a few applications of typedef in C++:

01) Using typedef with predefined data types

We have predefined data types like int, char, float, and their derivatives like long, short, signed, and unsigned. We can use typedef for aliasing them as seen above. 

Syntax:

typedef <data_type_name> <new_name>

 

 Example:

// Welcome to FavTutor
// C++ for using typedef with predefined data types
#include

using namespace std;

int main()
{
	// ulli can now be used for making more
	// unsigned long long int type variables
	typedef unsigned long long int ulli;
	// ulli used to make variables
	ulli a{ 1232133 };
	cout << a;
	return 0;
}

 

Output:

1232133

 

02) Using typedef with STL data structures

 We have STL Data Structures, like Vectors, Strings, Maps, etc.  If we are one of those, who do not want to import the entire std namespace in our code, then we need to write std::vector, std::string, etc, again and again. Instead, typedef will do our job easier.

 Syntax:

typedef <data_structure_name> <new_name>

 

Example:

// Welcome to FavTutor
// C++ Program to display usage for typedef with vectors
#include
#include 

int main()
{
	// Now we can make more vectors by using vInt
	typedef std::vector<int> vInt;
	// vec1 is a vectorof type int
	vInt vec1{ 1, 2, 3, 6, 2, 1 };

	// Outputting the vector
	for (int i = 0; i < vec1.size(); i++) {
		std::cout << vec1[i] <<" ";
	}
	return 0;
}

 

Output:

1 2 3 6 2 1 

 

03) Using typedef with arrays

We can easily make new arrays or make arrays of arrays using typedef with arrays, while keeping our code readable, seamlessly.

After this  can now be used for creating arrays of type-  and size .

Syntax: 

typedef <data_type> <alias_name> [<size>]

 

Example:

// Welcome To FavTutor
// C++ program to show use of typedef with arrays
#include 
using namespace std;

int main()
{

	typedef int arr[3];

	// Making new 1D array

	arr array1{ 1 , 1, 1};
	

	cout << "Array output: "
		<< "\n";
	for (int i = 0; i < 3; i++) {
		cout << array1[i] << " ";
	}
	cout << "\n";

	// Making new 2D array
	// Matrix is an array of arrays with size
	// ( 3 X 3 )
	arr matrix[3];

	cout << "Matrix output: "
		<< "\n";

	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			// Initializing the matrix
			matrix[i][j] = i * j;
		}
	}

	// Outputting the matrix

	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			cout << matrix[i][j] << " ";
		}
		cout << "\n";
	}

	return 0;
}

 

Output:

Array output: 
1 1 1 
Matrix output: 
0  0  0  
0  1  2  
0  2  4

 

04) Using typedef with pointers

For faster creation of pointers, and keeping the code readable as well. We can use them with both data pointers as well as function pointers.

Case 01: Usage with data pointers

 Syntax:

typedef <data_type>* <alias_name>

 

Example:

typedef int* iPtr;
iPtr pointer1, pointer2;

 

Below is the program to use typedef with data pointers.

// Welcome to Favtutor
// C++ Program to showcase the use of typedef
// with data pointer

#include
using namespace std;

int main()
{
	int a = 10;
	int b = 20;
	// iPtr can now be used to create new pointers of type
	// int
	typedef int* iPtr;

	iPtr pointer_to_a = &a;
	iPtr pointer_to_b = &b;

	cout << "a is: " << *pointer_to_a << "\n";
	cout << "b is: " << *pointer_to_b << "\n";

	return 0;
}

 

Output:

a is: 10
b is: 20

 

Case 02: Usage with fucntion pointers

Syntax:

typedef <return_type> (*<alias_name>)(<parameter_type>,<parameter_type>,....);

 

Example:

typedef int (*fun_ptr)(int, int);
fun_ptr new_ptr = &function; 

 

This will be more clear in the code below:

// Welcome to Favtutor
#include

// Normal pointer to a function
int (*func_ptr1)(int, int);

// Using typedef with pointer to a function
typedef int (*func_ptr2)(int, int);

// Function to multiply two numbers
int product(int u, int v) { return u * v; }

int main(void)
{
	func_ptr1 = &product;

	// Using typedefed function pointer for creating new
	// function pointer "new_func"
	func_ptr2 new_func_ptr = &product;

	// Using normal pointer to a function
	int x2 = (*func_ptr1)(3, 2);

	// Using the new function pointer
	int x1 = (*new_func_ptr)(2, 4);

	std::cout << x1 << std::endl;
	std::cout << x2 << std::endl;
}

 

Output:

8
6

 

Conclusion 

I hope you learn the fundamentals of typedef in C++ and now will be able to implement it as well in your code frequently wherever needed. So we see the typedef in detail and their applications with examples. It makes your code more readable for other users and can enhance code maintenance as well.

Congratulations on getting this far! Now give yourself a pat on the back. Good job!

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Anubhav Agarwal
I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for.