Complementary task for topic: 5
M Nemeth · 2023-08-29 15:21:04.621219'
Structs: Typedef and enum
Structs: Typedef and enum
Use typedef to change the name of struct Student type to Student. Use an enum for the houses!
Hint: Typedef is just a rename, nothing change, except we can handle and read the code more easily. enumerated data type is a user-defined (programmer defined) type containes named inetger values. In our case there will be 4 integer values (0,1,2,3) that renamed to Griffindor, Huffelpuff, Ravenclaw, and Slytherin. We can use the names in evaluations.
Solution
#include
enum House{
Griffindor,
Huffelpuff,
Ravenclaw,
Slytherin
};
typedef struct Student {
char name[100];//Max. 99 chars for a name!
int age;
float magic_attack;
float magic_defense, cleverness;
enum House house; //it is an enum, must be defined before first use!
}Student;
int main() {
Student Friends[3]={{"Harry Potter",12,55,70,35,Griffindor},{"Ronald Weasley",12,57,40,55,Griffindor},{"Hermione Granger",13,51,60,75,Griffindor}};
for(int i=0;i<3;i++){
printf("%s\n",Friends[i].name);
}
return 0;
}
Explanation
The modifications here: -We have used enum type for houses, that coud be typedefed too -We typedefed the struct so no need to use "struct Student", "Student" is enough, however you can use "struct Student" if you want. Another (and more popular) solution for typdef a struct: typedef struct { char name[100];//Max. 99 chars for a name! int age; float magic_attack; float magic_defense, cleverness; enum House house; //it is an enum, must be defined before first use! }Student; With this an anonymus struct is renamed, so "struct Student" cannot be used (as it was never existed)