typedef
 

  • Usage of the typedef mechanism:

      • A (user defined) struct type (and other data types) can be given a unique name (= "alias") using the typedef keyword

  • Syntax:

         typedef  dataType  alias 

  • Example:

         typedef  struct BankAccount  BankAccount_t ; 

    You can now use BankAccount_t in the place of struct BankAccount

Example of using typedef

 #include <stdio.h>

 struct BankAccount 
 {   
   int   ID;
   float balance;
 };

 typedef struct BankAccount BankAccount_t;

 void doubleBal( BankAccount_t x )
 {
    x.balance = 2*x.balance;
 }

 int main(int argc, char *argv[])
 {
   BankAccount_t john; // Local struct variable

   john.balance = 500;
   doubleBal( john );
   printf("%f\n", john.balance); // Prints 500 - unchanged !!
 }    

DEMO: demo/C/set2/typedef1.c

Combining typedef with a struct definition

  • You can use a typedef in combination with a struct definition as follows:

     typedef                  
          struct BankAccount    
          {                     
       	 int    ID;     
       	 double balance;    
          }                     
          BankAccount_t; 

  • The above is the same as:

      struct BankAccount    
      {                     
          int    ID;     
          double balance;    
      };
    
      typedef  struct BankAccount  BankAccount_t ;