w3resource

C Language: Difference between typedef struct and struct definitions with example

C - Difference between typedef struct and struct

In C language, struct is used to define a user-defined data type that groups together variables of different data types under a single name.
A typedef can be used to create an alias for an existing data type, including a struct.

Here is an example of using a struct definition to create a custom data type:

Code:

struct student {
   char name[50];
   int age;
   float height;
};
struct student s1 = {" Nina Chase", 12, 1.55};
struct student s2 = {" Shyann Morris", 12, 1.65};

In the above example, we define a struct called student that contains three member variables: name, age, and height. We then create two instances of the student struct called s1 and s2 and initialize its member variables.

Now let's see an example of using a typedef with a struct:

Code:

typedef struct {
   char name[50];
   int age;
   float height;
} student;

student s1 = {" Nina Chase", 12, 1.55};
student s2 = {" Shyann Morris", 12, 1.65};

In the above example, we define a typedef that creates an alias for a struct containing the same three member variables as before. We then create two instances of the student struct using the typedef aliases s1 and s2 and initialize its member variables.

The main difference between using typedef and struct directly is that typedef allows us to create an alias for the struct. This alias is then used later to define variables of that type without having to write the struct keyword.



Follow us on Facebook and Twitter for latest update.