x

C – Typedef

Prev     Next

  • Typedef is a keyword that is used to give a new symbolic name for the existing name in a C program. This is same like defining alias for the commands.
  • Consider the below structure.

struct student
{
         int mark [2];
         char name [10];
         float average;
}


  • Variable for the above structure can be declared in two ways.

1st way  :

struct student record;       /* for normal variable */
struct student *record;     /* for pointer variable */

2nd way :

typedef struct student status;

  • When we use “typedef” keyword before struct <tag_name> like above, after that we can simply use type definition “status” in the C program to declare structure variable.
  • Now, structure variable declaration will be, “status record”.
  • This is equal to “struct student record”. Type definition for “struct student” is status. i.e. status = “struct student”

An alternative way for structure declaration using typedef in C:

typedef struct student
{
         int mark [2];
         char name [10];
         float average;
} status;


  • To declare structure variable, we can use the below statements.

status record1;                 /* record 1 is structure variable */
status record2;                 /* record 2 is structure variable */

Example program for C typedef:

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000
  • Typedef can be used to simplify the real commands as per our need.
  • For example, consider below statement.

typedef long long int LLI;

  • In above statement, LLI is the type definition for the real C command “long long int”. We can use type definition LLI instead of using full command “long long int” in a C program once it is defined.

Another example program for C typedef:

 

Output:

Storage size for long long int data type : 8

Prev     Next



Like it? Please Spread the word!