typedef datatype

Q . Write and explain the significance of "typedef datatype" in c programming with example.


Ans.


In C typedef is a keyword.


Keyword typedef stands for type definition.


It is used for create an alias name of existing data type. typedef is used by writing the keyword typedef, followed by the existing data type and then the new name.


Syntax:


typedef existing_daya_type new_name ;


Example:


typedef char ch;


In above example, i has defined ch as char, so now i could perfectly use ch as declarations of any other valid types:


ch yourchar;
ch mychar,*str;


Note:- typedef does not create different types. It only create synonyms of existing data types i.e. in our example the type of mychar can be considered to be either ch or char, since both are in fact the same type.


Example of typedef:


typedef int num;
num n1,n2,n3;


/*c program for shows the use of typedef data type */
#include<stdio.h>
#include<conio.h>
int main()
{
  typedef int number;
  number n1,n2,sum;
  printf("Enter n1 : ");
  scanf("%d",&n1);
  printf("Enter n2 : ");
  scanf("%d",&n2);
  sum=n1+n2;
  printf("sum of n1+n2 = %d",sum);
  getch();
  return 0;
}


/*************** OUTPUT ***************/
Example of typedef






typedef can be useful to define an alias for a type that is frequently used within a program.


typedef is also useful to define types when it is possible that we will need to change the type in later our program.


typedef is also used when existing_name is too large or confusing. 


Related post:

  1. enum
  2. struct
  3. union

Comments