Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
int do_work(int seconds_to_work) {
  time_t start = time(NULL);

  if (start == (time_t)(-1)) {
    /* Handle error */
  }
  while (time(NULL) < start + seconds_to_work) {
    /* ... */
  }
  return 0;
}

Compliant Solution

This compliant solution uses difftime() to determine the difference between two time_t values. difftime() returns the number of seconds from the second parameter until the first parameter and returns the result as a double.

Code Block
bgColor#ccccff
int do_work(int seconds_to_work) {
  time_t start = time(NULL);
  time_t current = start;

  if (start == (time_t)(-1)) {
    /* Handle error */
  }
  while (difftime(current, start) < seconds_to_work) {
    current = time(NULL);
    if (current == (time_t)(-1)) {
       /* Handle error */
    }
    /* ... */
  }
  return 0;
}

Note that this loop may still not exit, because the range of time_t may not be able to represent two times seconds_to_work apart.

...