// compare the date1.cpp and date2.cpp code to the // increment_date2.cpp code from lecture 18. // the main difference is that, in increment_date2.cpp, // the increment_date function does not change its argument, // but rather creates a new date object as a result. // // In date1.cpp, we show an INCORRECT version of // the increment_date function, that tries to modify its argument // and fails, because its argument is not a pointer. // // In date2.cpp, we show the CORRECTED version of // the increment_date function, that tries to modify its argument // and succeeds, because its argument is a pointer. #include // note that the structure date is defined in // the header file. #include "date2.h" // Note that this function works correctly. // Compare to the incorrect version at date1.cpp void increment_date(struct date * d1) { d1->day++; switch(d1->month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (d1->day == 32) { d1->day = 1; d1->month++; } break; case 2: if (d1->day == 29) { d1->day = 1; d1->month++; } break; default: if (d1->day == 30) { d1->day = 1; d1->month++; } } if (d1->month == 13) { d1->month = 1; d1->year++; } } struct date input_date() { struct date result; printf("please enter month day year:\n"); scanf("%d %d %d", &(result.month), &(result.day), &(result.year)); return result; } void print_date(char * name, struct date d1) { printf("%s = %d/%d/%d\n", name, d1.month, d1.day, d1.year); } struct date copy_date(struct date input) { struct date result = input; return result; } int main(void) { struct date d1 = input_date(); printf("before incrementing:\n"); print_date("d1:", d1); increment_date(&d1); printf("\nAfter incrementing:\n"); print_date("d1:", d1); // note that the date d1 has not changed. }