9.5. Modifiers

Of course, sometimes you want to modify one of the arguments. Functions that do are called modifiers.

As an example of a modifier, consider increment, which adds a given number of seconds to a Time object. Again, a rough draft of this function looks like:

void increment (Time& time, double secs) {
  time.second += secs;

  if (time.second >= 60.0) {
    time.second -= 60.0;
    time.minute += 1;
  }
  if (time.minute >= 60) {
    time.minute -= 60;
    time.hour += 1;
  }
}

The first line performs the basic operation; the remainder deals with the special cases we saw before.

Is this function correct? What happens if the argument secs is much greater than 60? In that case, it is not enough to subtract 60 once; we have to keep doing it until second is below 60. We can do that by replacing the if statements with while statements:

The active code below uses the increment function. Run the active code to see what the output is!

The solution above is correct, but not very efficient. Can you think of a solution that does not require iteration? Try writing a more efficient version of increment in the commented section of the active code below. If you get stuck, you can reveal the extra problem at the end for help.

You have attempted of activities on this page