9.6. Fill-in functionsΒΆ
Occasionally you will see functions like add_time written with a
different interface (different arguments and return values).
Instead of creating a new object every time add_time is called,
we could require the caller to provide an "empty" object where
add_time can store the result.
compare the following with the previous version:
void add_time_fill (const time& t1, const time& t2, time& sum) {
sum.hour = t1.hour + t2.hour;
sum.minute = t1.minute + t2.minute;
sum.second = t1.second + t2.second;
if (sum.second >= 60.0) {
sum.second -= 60.0;
sum.minute += 1;
}
if (sum.minute >= 60) {
sum.minute -= 60;
sum.hour += 1;
}
}
One advantage of this approach is that the caller has the option of reusing the same object repeatedly to perform a series of additions. This can be slightly more efficient, although it can be confusing enough to cause subtle errors. For the vast majority of programming, it is worth a spending a little run time to avoid a lot of debugging time.
The active code below uses the fill-in version of the add_time function.
Feel free to modify the code!
1#include <iostream>
2using namespace std;
3
4struct time {
5 int hour, minute;
6 double second;
7};
8
9void print_time (time& t) {
10 cout << t.hour << ':' << t.minute << ':' << t.second << '\n';
11}
12
13void add_time_fill (const time& t1, const time& t2, time& sum) {
14 sum.hour = t1.hour + t2.hour;
15 sum.minute = t1.minute + t2.minute;
16 sum.second = t1.second + t2.second;
17
18 if (sum.second >= 60.0) {
19 sum.second -= 60.0;
20 sum.minute += 1;
21 }
22 if (sum.minute >= 60) {
23 sum.minute -= 60;
24 sum.hour += 1;
25 }
26}
27
28int main() {
29 time current_time = { 5, 45, 30.0 };
30 time baking_time = {0, 55, 0.0 };
31 time finished_time; // We'll store the sum in this variable
32 add_time_fill (current_time, baking_time, finished_time);
33 cout << "The bread will be ready at ";
34 print_time (finished_time);
35}
Q1
Which parameter is not declared as a const?
void add_time_fill (const time& t1, const time& t2, time& sum) {
sum.hour = t1.hour + t2.hour;
sum.minute = t1.minute + t2.minute;
sum.second = t1.second + t2.second;
if (sum.second >= 60.0) {
sum.second -= 60.0;
sum.minute += 1;
}
if (sum.minute >= 60) {
sum.minute -= 60;
sum.hour += 1;
}
}