Jul 2, 2015

TYPEDEF - create variables by your name

Typedef:
          Typedef is a keyword used to assign new names to existing data types. This is same like defining alias for the commands.

typedef  existing_name alias_name;

After this statement, instead of existing_name we can use alias_name.
If we look at an example

          typedef int aj;
aj i , j;

The above statement define a term  aj  for an int type. Now this  aj  identifier can be used to define int type variables. This is also equal to int i , j;

          typedef unsigned long  int  ajj;
        ajj  i, j ;

After this type definition, the identifier ajj can be used as an abbreviation for the type unsigned long int.

Using typedef with structures :

You can use typedef to give a name to user defined data type as well. For example you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows:

typedef struct book
{
           int x;
           float y;
           char c[10];
} Book;
         
         Here Book is the structure_variable name and book is tag_name. After this definition, we can create structure variables with Book word instead of struct book.

For example:

 #include <stdio.h>
 #include <string.h>
 typedef struct Books
 {
          char title[20];  
          int pages;
 } Book;
int main( )
           {
           Book  book;
           strcpy (book.title, "C Programme");
                     book.pages = 230;
                     printf( "Book title : %s\n", book.title);
           printf( "no of pages : %d\n", book.pages);
                     return 0;
           }

In the above program we have defined Book book instead of struct books book.

·       Typedef can be used for pointers also.

                    typedef int *x , y;

By this definition, we can use x for defining pointer variables and y can be used for integer variables.

#include <stdio.h>
 #include <string.h>
int main( )
     {
              typedef int  *x , y;
              y  a = 10;
              x  b;
              b = &a;
              printf("%d",a);              //output : 10 10
              printf("%d",*b);
               return 0;

     }
Filed under ,  |