Skip to content

Typedef in C++

Reading Time: < 1 minute

The declaration that follows the keyword typedef is otherwise usual simple declaration (except that other type specifiers, e.g. static, cannot be used). It may declare one or many identifiers on the same line (e.g. int and a pointer to int), it may declare array and function types, pointers and references, class types, etc. Every identifier introduced in this declaration becomes a typedef-name rather than an object that it would become if the keyword typedef was removed.

The typedef-names are aliases for existing types, and are not declarations of new types. Typedef cannot be used to change the meaning of an existing type name (including a typedef-name). Once declared, a typedef-name may only be redeclared to refer to the same type again. Typedef names are only in effect in the scope where they are visible: different functions or class declarations may define identically-named types with different meaning.

An Typedef in C++ is a new name to the data type so that it can be identified using different identifier.

Example:

typedef int newval;

here int is a datatype it can also be referenced as newval hereafter.see below how it effects:

newval c;

here the variable c is declared with integer datatype using type definition.

Advantages of typedef:

1.Simplification.

2.Clarification.

3.Abstraction.

4.Easier code maintenance.

5.Portability.

6.Readability.

Typedef function Example:

typedef int (*ptrToFunct)(int, int);
//now on ptrToFunct can be used as a type 
int retSum(int n1, int n2) 
{
  return n1 + n2;
}
 
ptrToFunct pFunct = retSum;
...
int x2 = (*pFunct)(10, 20); // call retSum() to calculate 10+20

 

See also  Software Licensing- An Overview

 

 

Tags:

Leave a Reply