C - Data Type typedef Introduction

Introduction

The following code uses typedef to redefine int type.

Demo

#include <stdio.h> 

typedef int myInt; 

myInt main() //from   w  w  w  . ja  v  a 2s.c om
{ 
     myInt a = 2; 

     printf("Everyone knows that "); 
     printf("%d + %d = %d\n",a,a,a+a); 
     return(0); 
}

Result

The typedef statement defines the word myInt to be the same as the keyword int.

Anywhere you can use int in the code, you can use the word myInt instead.

typedef is used most often in defining structures.

For example, The following code shows to declare two structures nested in a third.

Demo

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

int main()//from  w  w w.  ja  v  a 2  s  . c om
{
    typedef struct id
    {
        char first[20];
        char last[20];
    } personal;

    typedef struct date
    {
        int month;
        int day;
        int year;
    } calendar;

    struct human
    {
        personal name;
        calendar birthday;
    };
    struct human president;

    strcpy(president.name.first,"George");
    strcpy(president.name.last,"Washington");
    president.birthday.month = 2;
    president.birthday.day = 22;
    president.birthday.year = 1732;

    printf("%s %s was born on %d/%d/%d\n",\
            president.name.first,
            president.name.last,
            president.birthday.month,
            president.birthday.day,
            president.birthday.year);

    return(0);
}

Result