/* person.c Jeff Ondich, 5 March 2022 A program to help us investigate how struct types are passed as parameters. */ #include #include #include #include #include #define MAX_NAME_LENGTH 32 typedef struct { char name[MAX_NAME_LENGTH]; int birth_year; int birth_month; int birth_day; } person_t; person_t create_person(char *name, int year, int month, int day) { person_t person; person.birth_year = year; person.birth_month = month; person.birth_day = day; if (name != NULL) { strncpy(person.name, name, MAX_NAME_LENGTH); person.name[MAX_NAME_LENGTH - 1] = '\0'; } return person; } // Returns true if person1 is (strictly) older than person2, false otherwise. int is_older(person_t person1, person_t person2) { // What happens if we uncomment this? // strcpy(person1.name, "Friedrich Schiller"); if (person1.birth_year != person2.birth_year) { return person1.birth_year < person2.birth_year; } if (person1.birth_month != person2.birth_month) { return person1.birth_month < person2.birth_month; } return person1.birth_day < person2.birth_day; } // Returns the specified person's age in whole years on the specified date. // Returns -1 if the person's birthdate is after the specified date. int age(person_t person, int year, int month, int day) { bool date_is_before_birthday = (month < person.birth_month) || (month == person.birth_month && day < person.birth_day); if (year < person.birth_year || (year == person.birth_year && date_is_before_birthday)) { return -1; } int years = year - person.birth_year; if (date_is_before_birthday) { years--; } return years; } void person_test() { person_t p1; p1 = create_person("Alan Turing", 1912, 6, 23); int age1 = age(p1, 2022, 3, 7); printf("%s is %d years old today\n", p1.name, age1); person_t p2; p2 = create_person("John von Neumann", 1903, 12, 28); int age2 = age(p2, 2022, 3, 7); printf("%s is %d years old today\n", p2.name, age2); if (is_older(p1, p2)) { printf("%s is older than %s\n", p1.name, p2.name); } else { printf("%s is older than %s\n", p2.name, p1.name); } } int main() { person_test(); return 0; }