In this post i want to discuss about typedef and other same keyword in c++.

Thetypedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types–it literally stands for “type definition”. Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.

Some syntax examples:


typedef type NewTypeName;

typedef unsigned int UnsignedInt;
typedef int int_t; // declares int_t to be an alias for the type int
typedef char char_t, *char_p, (*fp)(void); // declares char_t to be an alias for char
// char_p to be an alias for char*
// fp to be an alias for char(*)(void)

A typedef for a VLA can only appear at block scope. The length of the array isevaluated each time the flow of control passes over the typedef declaration, as opposed to the declaration of the array itself:

 
void copyt(int n) { typedef int B[n]; // B is a VLA, its size is n, evaluated now n += 1;
 B a; 
// size of a is n from before +=1 
int b[n]; // a and b are different sizes 
for (int i = 1; i < n; i++){
 a[i-1] = b[i]; } 

Typedef name may be an incomplete type, which may be completed as usual:

 typedef int A[]; // A is int[]
 A a = {1, 2}, b = {3,4,5}; //type of a is int[2], type of b is int[3]
 

We can use typedef to avoid writting “struct s”.

 // common C idiom to avoid having to write "struct S"
 typedef struct {int a; int b;} S, *pS; // the following two objects have the same type 
pS ps1; S* ps2; 

An other example is in below. Typedef can be used anywhere in the decl-specifier-seq.

 // typedef can be used anywhere in the decl-specifier-seq 
long unsigned typedef int long ullong; 
// more conventionally spelled "typedef unsigned long long int ullong;" 

Using typedef, we can make the declaration of function pointer easy and readable. The typedef is very helpful when we create an array of the function pointer or a function returns a function pointer.

</pre>
// typedef of array of function pointers
typedef int (*apfArithmatics[3])(int,int);

void *pvHandle = NULL;
int (*pf)(int) = (int (*)(int)) pvHandle;
or...
typedef int (*pf)(int);
pf JumptoApp = (pf)pvHandle;
<pre>

 

Some example in metaprogramming used type keyword.

// std::add_const, like many other metafunctions, use member typedefs
template&amp;lt; class T&amp;gt;
struct add_const {
typedef const T type;
};

typedef struct Node {
struct listNode* next; // declares a new (incomplete) struct type named listNode
} listNode; // error: conflicts with the previously declared struct name

For more info see these link1 and link2.

 

 

Tags , , , , , , , , , , , , , , , , , , , , ,


Leave a Reply

Want to see your ugly mug by your comment? Get a free custom avatar at Gravatar.