Here are simple examples of using typedef with both struct and enum to make the code cleaner and easier to understand.

Example 1: typedef with struct
Instead of writing struct repeatedly, you can use typedef to create an alias for a struct.

c
Copy
Edit
#include <stdio.h>

// Define a structure for a point in 2D space
typedef struct {
    int x;
    int y;
} Point;

int main() {
    Point p1 = {10, 20};
    printf("Point: (%d, %d)\n", p1.x, p1.y);
    return 0;
}
Explanation:

typedef gives the alias Point to the structure.
You don’t need to write struct every time you declare a variable of this type.
Example 2: typedef with enum
You can use typedef to simplify working with enumerations.

c
Copy
Edit
#include <stdio.h>

// Define an enum for days of the week
typedef enum {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
} Day;

int main() {
    Day today = WEDNESDAY;
    if (today == WEDNESDAY) {
        printf("It's midweek!\n");
    }
    return 0;
}
Explanation:

typedef gives the alias Day to the enumeration.
You don’t need to write enum every time you declare a variable of this type.
Summary:
Use typedef with struct to avoid repeatedly typing struct when declaring variables.
Use typedef with enum to simplify the syntax when using enumerations.
Both examples showcase how typedef improves code readability and reduces verbosity.

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: