typedef in C language: 7 application you should know

typedef in c

If you are fresher, then definitely a question comes in your mind what is typedef in C and why we use typedef in C programming. If you are looking for these questions like how to use typedef in c,  what is typedef in C or why we use typedef in C, then you are at the right place. Here I will discuss all small and big things related to the C typedef. So let us come on the topic.

What is typedef in C?

A typedef defines a new name for existing types and does not introduce a new type. It is the (partial storage-class specifier) compiler directive mainly use with user-defined data types (structure, union or enum)) to reduce their complexity and increase code readability and portability.

In C programming, we can use typedef declarations to create shorter or more meaningful names for types already defined by C (inbuilt data types like int, char, float) or for types that you have declared.

 

Syntax of typedef in C:

typedef   type   NewTypeName;

 

We can see that the declaration of typedef looks like the declaration of a variable but in the case of the typedef, the identifier becomes a synonym for the type.  Let us see an example,

typedef unsigned int UnsignedInt;

 

Now UnsignedInt becomes a synonym of unsigned int and we can use UnsignedInt in place of unsigned int.

UnsignedInt Mydata;

 

Note:  A typedef creates synonyms or a new name for existing types it does not create new types.

 

Why we use typedef in C?

There might be many reasons but here I am explaining two important reasons why we should use typedef in C programming. If you know more reasons, then please write it in the comment box it will help others.

Code Portability

We know that the size of the int is not specified by the C standard. The  C standard only explained the minimum size of the integer that is 16 bits. So if you working on a platform for where you want the size of int is always 32 bits, so in that situation typedef is useful. Let us see an example, where int size is always 32 bits with the help of a typedef.

#ifdef AVR_32
typedef  int int_32
#else
typedef long int_32  
#endif

 

Code Readability:

Consider the below declaration,

int(*(*pf())[4])();

Here, pf is a function returning a pointer to an array whose size is 4 and contains pointers to function returning an int. Let use see code without the typedef.

#include<stdio.h>

int testFun1()
{
    return 1;
}
int testFun2()
{
    return 2;
}
int testFun3()
{
    return 3;
}
int testFun4()
{
    return 4;
}

//global Array contain function pointers
int (*arr[4])() = {testFun1,testFun2,testFun3,testFun4};


//function return array of function pointers
int(*(*pf())[4])()
{
    //Array of function pointers
    int (*(*pfArr)[4])() = &arr;

    return(pfArr);
}


int main()
{
    int (*(*test)[4])() = pf();

    //print function return value
    printf("%d\n",(*test)[0]());
    printf("%d\n",(*test)[1]());
    printf("%d\n",(*test)[2]());
    printf("%d\n",(*test)[3]());

    return 0;
}

Output:

typedef in c programming

 

We can make the above declaration understandable and increase the code readability using the typedef in C. Please see the example below.

#include<stdio.h>

int testFun1()
{
    return 1;
}
int testFun2()
{
    return 2;
}
int testFun3()
{
    return 3;
}
int testFun4()
{
    return 4;
}

//fun is the type of pointer to function returning int
typedef int (*fun)();

//pArrfun is the type of pointer to array whose size is 4 and
//which contains fun which is pointers to functions returning int
typedef fun (*pArrfun)[4];


//global Array contain function pointer
fun arr[4] = {testFun1,testFun2,testFun3,testFun4};

//pf is function which return pArrfun
pArrfun pf()
{
    //Array of function pointers
    pArrfun pfArr= &arr;

    return(pfArr);
}


int main()
{
    pArrfun test = pf();

    printf("%d\n",(*test)[0]());
    printf("%d\n",(*test)[1]());
    printf("%d\n",(*test)[2]());
    printf("%d\n",(*test)[3]());

    return 0;
}

Output:

typedef in c programming

Code Clarity:

A typedef is increased the code readability to give the new name to a complex declaration. In the case of the structure and union, it is very good to use a typedef, it helps to avoid the struct keyword at the time of variable declaration. You can also give a meaningful name to an existing type (predefined type or user-defined type).

Let’s take an example
Suppose there is a structure, which contains the information of a student.

struct sStudentInformations
{
    int iRollNumber;
    char acName[30];
    int  iTotalMarks;
};

 

Whenever in the program we need to declare a variable of the above structure than every time we have to write the struct keyword with the tag name.

struct sStudentInformations aticleworld;

 

But if we are used the typedef with the above structure then there is no need to write struct keyword at the time of variable declaration.

typedef struct sStudentInformation
{
    int iRollNumber;
    char acName[30];
    int  iTotalMarks;
} sStudentInformation;

Now sStudentInformation is new types and whenever in the program we need the above structure variable then no need to write the struct.

sStudentInformation   aticleworld;

 

Scope of typedef in C

Good thing is that the typedef follows the scope rules. It means, it can have block scope, file scope, etc. If we want we can use the same name for typedef in different scope. Let us see examples to understand how the typedef in C follows the scope rule.

Example Code when typedef in different Scope:

 

#include <stdio.h>
#include <stdlib.h>


// define new type for int
typedef int INT;

int AdditionOfTwoNumber(void)
{
    INT a =0,b =0;

    printf("Enter two number\n\n");
    scanf("%d%d",&a,&b);

    return (a+b);
}

int main(int argc, char *argv[])
{
    // define new type for char *
    //Using Same Name INT
    typedef char * INT;

    INT pcMessage = "aticleworld";

    printf("\n\nDisplay Message = %s\n\n",pcMessage);

    printf("Addition of two number = %d\n\n",AdditionOfTwoNumber());

    return 0;
}

OutPut:

 

 

Explanation of the code

We can see that in the code INT is using with typedef for two different types int and char *. We are not getting compiler error because both INT has a different meaning in different scope. Globally INT behaves like int but in the main function, it behaves like the char *.

Example code when typedef in the same Scope:

 

#include <stdio.h>

int main(int argc, char *argv[])
{
    // define new type for char *
    typedef char * TypeName;

    // define new type for int
    // Using same name TypeName
    typedef int TypeName;

    TypeName iData = 4;

    printf("Display Message = %s\n\n",iData);

    return 0;
}

OutPut:

Explanation of the code

Both typedef in the same scope with same name (TypeName). So here compiler getting confuses and giving the error, see the error message.

 

If you want to learn more about the c language, here 10 Free days  C video course for you.

C tutorial

 

Application of typedef in C

typedef keyword is used in many places in C programming. But mostly it uses with user-defined data types like structure, union or enum.  So here, we are going to discuss some places where you can use typedef wisely which increases the code readability and complexity.

 

Use of typedef with predefine data types:

Some time to increase the code readability and portability we need to use the typedef with predefined data types. Let us see few examples to understand this concept.

Suppose you are working on an application which used to measure the distance. So beside using the unsigned int, you can create own types with a meaning full name using the typedef. In the below example, we are creating own type distance.

typedef  unsigned int distance;

distance KiloMeter = 10;
distance Meter = 5;
distance Miles = 7;

At the beginning of the article, I have already discussed how you can increase the code portability using the typedef.

Use of typedef with pointers

In C programming, we can use the typedef with pointers. Let us see an example,

typedef int * intPtr;

typedef char* charPtr;

After the above statement, intPtr becomes an alias of a pointer to int and charPtr becomes an alias of a pointer to char.  So if we need to declare the pointer to int or pointer to char, then we can declare it without using the asterisk (*) symbol. So let us see how we can declare a pointer to int or pointer to char using the intPtr or charPtr.

intPtr ptr;

charPtr cPtr;

 

Above declaration is same as:

int * ptr;

char* cPtr;

 

Let us see example code for better understanding,

#include<stdio.h>

typedef int * intPtr;
typedef char * charPtr;

int main()
{
    int data = 27;
    //Create char and int pointer
    intPtr ptr = NULL;
    charPtr cPtr = "Aticleworld.com";
    //Assign data address to ptr
    ptr = &data;

    //print the value
    printf("%u\n", *ptr);
    printf("%s\n", cPtr);

    return 0;
}

Output:

typedef pointer in c

 

Use of  typedef with a structure

When we used typedef with structure then there is no need to write struct keyword at the time of variable declaration. It saves the extra keystroke and makes the code cleaner. Let us see the example,

struct sStudentsInformations
{
    char acName[20];
    int iAge;
    int iTotalMarks;
};


typedef  struct  sStudentsInformations   sStudInfo;

After this declaration, sStudInfo is an alias of struct sStudentsInformations. So instead of using struct sStudentsInformations to declare new structure variables we can use just use sStudInfo.

 

We can also combine a structure definition with a typedef. Let us see the syntax,

typedef struct sStudentsInformations
{
    char acName[20];
    int iAge;
    int iTotalMarks;
} sStudInfo;

 

If we used a typedef with the structure definition, then we can also remove the structure tag.

typedef struct
{
    char acName[20];
    int iAge;
    int iTotalMarks;
} sStudInfo;

 

But it is my recommendation to use the structure tag at the time of the structure declaration. Because if we have not used a structure tag with structure then we will get a compiler error when structure tries to reference itself.

typedef struct
{
    char acName[20];
    int iAge;
    int iTotalMarks;
    sStudInfo *Info; // error
} sStudInfo;

 

But if we used a structure tag with the above code then it will work fine.

typedef struct sStudentsInformations
{
    char acName[20];
    int iAge;
    int iTotalMarks;
    struct  sStudentsInformations *Info;  // fine
} sStudInfo

 

Use of typedef with structure pointer

We can also use a typedef with a structure pointer and avoid the use of struct keyword at the time of the structure pointer declaration. Let us see the example,

typedef struct sStudentsInformations sStudInfo;

struct sStudentsInformations
{
    char acName[20];
    int iAge;
    int iTotalMarks;
    sStudInfo *psList;  // fine
};

 

We can create different types using the typedef with structure definition. See the below example in which we are creating two types one is structure pointer and the second is structure variable.

typedef struct sStudentsInformations
{
    char acName[20];
    int iAge;
    int iTotalMarks;
    struct sStudentsInformations *psList;  // fine
} sStudInfo,*psStudInfo;


psStudInfo Ram; //similar to struct sStudentsInformations * Ram.

sStudInfo  Shyam;//similar to struct sStudentsInformations Shyam.

 

Use of typedef with arrays:

We can use a typedef with an array. It increases the readability.  Some times in the code we need to create a multi-dimension array.  We know that the handling of a multidimensional array is complicated. It becomes more dangerous when we need to pass a multidimensional array in the function. So let us see an example where we are using a typedef with an array and passing this array in function by the call by reference.

#include <stdio.h>

//Use typedef
typedef  int Brick_Price[3];

void InitBrickPrice( Brick_Price *paPrice)
{
    (*paPrice)[0] = 10;
    (*paPrice)[1] = 20;
    (*paPrice)[2] = 30;
}


int main(int argc, char *argv[])
{
    int i =0;
    Brick_Price price;

    //Init Price
    InitBrickPrice(&price);

    while(i < 3)
    {
        printf("Brick Price%d : %d\n\n",i,price[i++]);
    }

    return 0;
}

OutPut:

 

 

Code Explanation:

In the above example, InitBrickPrice is the function that takes the pointer to the array as arguments and initializes the passed array with a defined price. After using the typedef Brick_Price becomes an array of three integers.

Brick_Price *paPrice is similar to int (*paPrice) [3];

 

Use of typedef with the 2D  array,

typedef int iaData[2][2];
//Here Mydata treat as 2D array
iaData Mydata;
//Here paMydata treat as the pointer to the 2d array.
iaData *paMydata;

 

Use of typedef with the function pointer

Using a 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. Let us see the example,

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

Now, apfArithmatics is a type of array of a function pointer and we can create a variable using this created type. Let us see the example where we have created a variable and initializing it by three functions AddTwoNumber, SubTwoNumber, and MulTwoNumber.

apfArithmatics aArithmaticOperation = { AddTwoNumber,SubTwoNumber,MulTwoNumber };

 

Some times in the code we need to typecast the address using the function pointer. It also becomes easy using the typedef.

void *pvHandle = NULL;

int (*pf)(int) = (int (*)(int)) pvHandle;

Now using typedef,

typedef int (*pf)(int);

pf JumptoApp  =  (pf)pvHandle;

 

 

Use of typedef enum in C

We can use the typedef and enum together in C programming.  If we use typedef with enum in C then it increases the code readability and creates a new type for the enum. Let see an example, where I am creating a list of errors using the enum and defining a new type using the typedef.

#include <stdio.h>
//typedef enum together
typedef enum
{
    NoError = 0,
    ReadError,
    WriteError,
    FlashError,
    LogError
} eErrorList;

//enum variable
eErrorList flashState;

int main(int argc, char *argv[])
{
    flashState = NoError;
    while(1)
    {
        //code
    }
    return 0;
}

 

typedef vs #define

  • The typedef has the advantage that it obeys the scope rules that means you can use the same name for the different types in different scopes. typedef can have file scope or block scope in which it is used. In other words, #define does not follow the scope rule.
  • typedef is compiler token while #define is a preprocessor token.
  • typedef is ended with semicolon while #define does not terminate with a semicolon.
  • typedef is used to give a new symbolic name to the existing type while #define is used to create an alias of any type and value.

 

Advantages of typedef

  • Increase the readability of the code. If you are using structure and function pointer in your code, you should use typedef it increaser the readability.
  • typedef obeys the scope rules which means you can use the same name for the different types in different scopes.
  • Using the typedef we can remove the extra keystroke, for example in structure if you will use the typedef then you do not require to write struct keyword at the time of variable declaration.
  • It increases the portability of the code.

Recommended Post

Important: We have prepared a quiz on typedef mention below

QUIZ on typedef



14 comments

  1. Hi Amlendra,

    Very nice article.

    I have one query related to below example that you have mentioned above. ??

    unsigned int KiloMeter;
    unsigned int Meter;
    unsigned int Miles;

    void SpeedCalculator(void)
    {
    int KiloMeter = 100; (Why here int need to use, in point of view its not needed.)
    //calculate speed in km/hr
    }

    int KiloMeter = 100; (Why here int need to use, in point of view its not needed.)

    Please correct me if i am wrong.

Leave a Reply

Your email address will not be published. Required fields are marked *