Skip to main content

Command Palette

Search for a command to run...

Declaring New Data Types with typedef

Updated
2 min readView as Markdown
Declaring New Data Types with typedef
  • typedef is a powerful tool that allows programmers to define and then use their own data types. For example:

    typedef int Integer;

    Integer nStudents, nCourses, studentID;

  • Note that in the typedef statement, the newly defined type name goes in the place where a variable name would normally go.

  • There are a few benefits of using typedef with simple types such as the example above:

    • For readability, "Integer" may be easier to understand than "int".

    • The typedef can be easily changed later, ( say to typedef long int Integer; ), which would then affect all variables of the defined type.

#include <stdio.h>

typedef long long int Integer;

int main(void) {
    Integer n;
    printf("Enter the value of n:");
    scanf("%lld",&n);
    printf("\nThe number is: %lld",n);

    return 0;
}

Output:

The real benefit of typedef comes into play with complex data structures, such as structs. Say we have a Point structure:

struct Point
{
    int x;
    int y;
} A;

int main(){
    printf("Enter the x-coordinate");
    scanf("%d",&A.x);
    printf("Enter the y-coordinate");
    scanf("%d",&A.y);
    printf("\nThe point A is (%d,%d).",A.x,A.y);

    struct Point B;

    printf("\nEnter the x-coordinate");
    scanf("%d",&B.x);
    printf("Enter the y-coordinate");
    scanf("%d",&B.y);
    printf("\nThe point B is (%d,%d).",B.x,B.y);
}

With typedef :

typedef struct Point
{
    int x;
    int y;
} Location;

int main(){
    Location A;

    printf("Enter the x-coordinate");
    scanf("%d",&A.x);
    printf("Enter the y-coordinate");
    scanf("%d",&A.y);
    printf("\nThe point A is (%d,%d).",A.x,A.y);

    Location B;

    printf("\nEnter the x-coordinate");
    scanf("%d",&B.x);
    printf("Enter the y-coordinate");
    scanf("%d",&B.y);
    printf("\nThe point B is (%d,%d).",B.x,B.y);
}

Even this is allowed:

typedef struct Point
{
    int x;
    int y;
} Point;

int main(){
    Point A;

    printf("Enter the x-coordinate");
    scanf("%d",&A.x);
    printf("Enter the y-coordinate");
    scanf("%d",&A.y);
    printf("\nThe point A is (%d,%d).",A.x,A.y);

    Point B;

    printf("\nEnter the x-coordinate");
    scanf("%d",&B.x);
    printf("Enter the y-coordinate");
    scanf("%d",&B.y);
    printf("\nThe point B is (%d,%d).",B.x,B.y);
}

typedef saves some typing and makes the code clearer to read.

23 views

More from this blog

P

Programming Tutorials

89 posts