Section 25.2 typedef
It is even possible to define a new data type and associate it with our new data structure. The C-command to do so is
typedef. The code window below shows the use of typedef in order to assign the name student_t to the more cumbersome student structure struct student. This way we can use the new data type student_t just like any of the C pre-defined data types int, float, double, char, void of which we know so far.
Just to remind you that you are dealing with a data type we’ll adopt the custom of always ending such a new data type name with “_t” as exemplified in the name
student_t for our new student record data type.
Compile and run the code below in your own C environment.
#define STRLEN 50
#include <stdio.h>
struct student{
char firstName[STRLEN];
char lastName[STRLEN];
int birthYear;
double aveGrade;
};
typedef struct student student_t;
int main(void) {
student_t me={"Petra", "Bonfert-Taylor", 1989, 3.5};
student_t you={"Karin", "Berger", 2005, 3.5};
printf("Name: %s %s\n", me.firstName, me.lastName);
printf("Year of birth: %d\n",me.birthYear);
printf("Average grade: %.2lf\n",me.aveGrade);
printf("\n");
printf("Name: %s %s\n", you.firstName, you.lastName);
printf("Year of birth: %d\n",you.birthYear);
printf("Average grade: %.2lf\n",you.aveGrade);
return 0;
}
Subsection 25.2.1 Alternative Method
You can actually combine the structure declaration and the
typedef into one more straight-forward method. The code window below shows you how to do so. The reason for introducing both the more cumbersome and the more straight-forward methods is that we will actually need the more cumbersome method later when we get to the topic of “linked lists”. For now I recommend that you go with the straight-forward method.
Compile and run the code below in your own C environment.
#define STRLEN 50
#include <stdio.h>
typedef struct {
char firstName[STRLEN];
char lastName[STRLEN];
int birthYear;
double aveGrade;
} student_t;
int main(void) {
student_t me={"Petra", "Bonfert-Taylor", 1989, 3.5};
student_t you={"Karin", "Berger", 2005, 3.5};
printf("Name: %s %s\n", me.firstName, me.lastName);
printf("Year of birth: %d\n",me.birthYear);
printf("Average grade: %.2lf\n",me.aveGrade);
printf("\n");
printf("Name: %s %s\n", you.firstName, you.lastName);
printf("Year of birth: %d\n",you.birthYear);
printf("Average grade: %.2lf\n",you.aveGrade);
return 0;
}

