...
This noncompliant code example attempts to execute do_work() multiple times until at least seconds_to_work has passed. However, because the encoding is not defined, there is no guarantee that adding start to seconds_to_work will result in adding seconds_to_work seconds.
| Code Block | ||||
|---|---|---|---|---|
| ||||
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;
}
|
...
This compliant solution uses difftime() to determine the difference between two time_t values. The difftime() function returns the number of seconds from the second parameter until the first parameter and result as a double.
| Code Block | ||||
|---|---|---|---|---|
| ||||
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;
}
|
...