The typedef
declaration provides a way to declare an identifier as a type alias in C/C++. It is used to replace a possibly complex type name. We can also use #define for defining alias.
typedef char char_t, *char_p, (*fP)(void);
Above example 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) i.e. function pointer which returns char
Usage in struct
typedef char char_t, *char_p, (*fP)(void); char func(void){ return 'c'; } // Equivalent to // typedef struct Point Point; typedef struct Point{ int a; int b; Point *next; } Point; // Common idiom to avoid having to write "struct S" typedef struct { int a; int b; } S, *pS; //Following two objects have the same type pS ps1; S* ps2; // A is int[] typedef int A[]; // type of a is int[2] and type of b is int[3] A a = {1, 2}, b = {3,4,5}; // Example showing discussed so far int main() { char_t c; char_p p = &c; Point point; fP f = &func; return 0; }
typedef
means you no longer have to write
all over the place as shown in the above example. struct
struct
defines a tag name, which is not a type name. So below will through error
struct Point{ int a; int b; Point *next; }; Point point; // compile error! struct Point point; // this is correct
Usage in Function Pointer
Below example shows the application of the typedef in declaring and using function pointer.
float doMultiplication (float num1, float num2 ) { return num1 * num2; } // Defining a pointer to a function which returns a float and takes two parameters, each of type float. typedef float(*pt2Func)(float, float); pt2Func *myFnPtr = &doMultiplication; // Invoking doMultiplication float result = (*myFnPtr)(2.0, 5.1);