CodeBlanks Logo Icon CodeBlanks

typedef and struct

  • C course
  • Intermediate
  • Lesson 106/116
  • 4 min

Learn to give a struct a short name with typedef.

typedef and struct

typedef gives a new name to a type. Used with struct, it saves you from writing struct every time. Declaration: typedef struct { ... } Person;.

Example: typedef struct { char name[32]; int age; } Person;. From then on you write Person p; instead of struct Person p;. This shortens code and improves readability. The type name is defined once and used throughout the program with the short name. This pattern is the foundation of data abstraction in C and gives consistent type names in large projects.

The Person struct

A Person struct holds name and age fields together. After defining with typedef, declaring variables and accessing fields becomes easy.

Example: Person p = {"Ayşe", 25}; creates a person. p.name gives the name, p.age the age. printf("%s %d\n", p.name, p.age); prints both fields. Values in braces map to the struct fields in order. This is the standard C way to represent record-like data; each field carries one attribute.

Practice Write the Person struct

Define typedef struct { char name[32]; int age; } Person;. In main create Person p = {"Ayşe", 25};. Print with printf("%s %d\n", p.name, p.age);.

Starter code

main.c
#include <stdio.h>

// Define the Person struct with typedef
// Create a Person variable in main and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

typedef struct {
    char name[32];
    int age;
} Person;

int main(void) {
    Person p = {"Ayşe", 25};
    printf("%s %d\n", p.name, p.age);
    return 0;
}

Expected output

Ayşe 25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does typedef struct provide?

  • Less memory usage
  • Faster compilation
  • Avoids writing struct every time Correct answer
  • Automatic cleanup

Explanation: typedef avoids repeating the struct keyword.

2 Complete the Person variable

Question
Person p = {"Ayşe", ____};
Answer
Person p = {"Ayşe", 25};

Explanation: Person p = {"Ayşe", 25}; creates the person.

3 Match the typedef struct parts

Term Meaning
typedef Naming
struct Struct definition
Person Short name
p.name Field access

All lessons in Intermediate