a shot of dev knowledge

RELATED TAGS

How to use the typedef struct in C

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types.

Remember, this keyword adds a new name for some existing data type but does not create a new type.


Syntax

svg viewer

Using typedef struct results in a cleaner, more readable code, and saves the programmer keystrokes​. However, it also leads to a more cluttered global namespace which can be problematic for large programs.


Examples

The following code snippets illustrate how to use the typedef struct.

1. Variable declaration without using typedef:

#include<stdio.h>

struct Point{
  int x;
  int y;
};
int main() {
    struct Point p1;
    p1.x = 1;
    p1.y = 3;
    printf("%d \n", p1.x);
    printf("%d \n", p1.y);
    return 0;
}

2. Using the typedef keyword:

Note that there is no longer a need to type struct again and again with every declaration of the variable of this type.

Method one:

#include<stdio.h>

struct Point{
  int x;
  int y;
};
typedef struct Point Point;
int main() {
    Point p1;
    p1.x = 1;
    p1.y = 3;
    printf("%d \n", p1.x);
    printf("%d \n", p1.y);
    return 0;
}

Method two:

#include<stdio.h>

typedef struct Point{
  int x;
  int y;
} Point;
int main() {
    Point p1;
    p1.x = 1;
    p1.y = 3;
    printf("%d \n", p1.x);
    printf("%d \n", p1.y);
    return 0;
}

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring