C++ Tutorials



Tutorials > C++ > Typedef

View Full Source

What does typedef do?

The typedef keyword allows you to specify another name for a particular data type. This allows your code to be simpler by reducing the number of keywords you need to specify for each variable you declare. You create a typedef by placing the typedef keyword, followed by the usual way you declare a variable. Instead the place where you put the variable name is now used as the typedef name. This should be more clear in the examples below.

Contents of main.cpp :

#include <iostream>
#include <stdlib.h>

using namespace std;

2 examples of using typedef are shown below. The first allows you use ushort instead of unsigned short where the second allows you to use chrp instead of char *. As you can see, typedefs are not necessary although you may find that they make your programs easier to understand.

// Type definitions
typedef unsigned short ushort;
typedef char *chrp;

int main()

Below you can see how variables can now be declared in the usual way, except submitting the data type for your own name given when defining a typedef.

	ushort num = 45;
	cout << num << endl;

	chrp msg = "Hello World";
	cout << msg << endl;


	return 0;

You should now be able to use the typedef keyword to make your code simpler and easier to read.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 25 - Multi-Dimensional Arrays Tutorial 27 - Structures >

Back to Top

All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer