Friday, 2 July 2010

typedef

You can define new data type names by using the keyword typedef

You are not actually creating a new data type.
You define a new name for an existing type.
Syntax:

typedef existing_name alias_name

The primary advantage of the type definition is that it allows you to replace a complex name, such as a pointer declaration, with a mnemonic that makes the program easier to read and follow.

Example:
typedef   float   AVERAGE;

AVERAGE  over_due;

typedef can be used to give a name to user defined data type as well. Lets see its use with structures.
typedef struct
{
type member1;
type member2;
type member3;
} type_name ;
Here type_name represents the stucture definition associated with it. Now this type_name can be used to declare a variable of this stucture type.
type_name t1, t2 ;
 

#include<stdio.h>
#include<conio.h>
#include<string.h>

typedef struct student
{
 char  name[50];
 int   marks;
} stud ;

void main( )
{
 stud e1;
 printf("\nEnter Student record\n");
 printf("\nStudent name\t");
 scanf("%s",e1.name);
 printf("\nEnter Student Marks \t");
 scanf("%d",&e1.marks);
 printf("\nStudent name is %s",e1.name);
 printf("\nMarks is %d",e1.marks);
 getch();
}

typedef can be used to give an alias name to pointers also.
int* a, b ;
By this declaration statement, we are actually declaring a as a pointer of type int, whereas b is declared as a normal integer.
typedef int* IntPtr ;
IntPtr a, b, c;
But if we use typedef like in above example, we can declare any number of pointers in a single statement.


You may like the following posts:
structures

No comments:

Post a Comment