11

From difftime()'s man page:

double difftime(time_t time1, time_t time0);

The difftime() function returns the number of seconds elapsed between time time1 and time time0, represented as a double.

Since 'number of seconds' doesn't require floating-point numbers, why does this function return a double?

edmz
  • 8,220
  • 2
  • 26
  • 45
Zaxter
  • 2,939
  • 3
  • 31
  • 48

2 Answers2

4

This documentation is more clear on the point:

On POSIX systems, time_t is measured in seconds, and difftime is equivalent to arithmetic subtraction, but C and C++ allow fractional units for time_t.

Although POSIX requires time_t to be an integer type, for non-POSIX systems it is possible that this can return fractional seconds.

J...
  • 30,968
  • 6
  • 66
  • 143
  • 1
    The standard says time_t can be: `Arithmetic (until C11) Real (since C11) type capable of representing times`. – Zaxter Dec 24 '15 at 21:30
  • @user3490458: Yes, but POSIX specifically requires `time_t` to be an integer type. http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_types.h.html – Keith Thompson Dec 25 '15 at 02:00
  • 1
    Yes, but you didn't *quite* make that point explicitly. An implementation could define `time_t` as `double` and still measure time in seconds. POSIX doesn't permit that, but you didn't say so. – Keith Thompson Dec 25 '15 at 03:20
  • @KeithThompson The question is tagged `posix`... I just assumed that was the frame of reference that we were working in (ie: the question is only puzzling if we're starting from the notion that `time_t` is an integer...otherwise, why would OP be confused?) – J... Dec 25 '15 at 13:04
  • 2
    Here's my point. POSIX requires `time_t` to be an integer type, which is relevant to the question. But your answer doesn't actually say that. It says that `time_t` is measured in seconds, but that's consistent with POSIX permitting `time_t` to be a floating-point type. – Keith Thompson Dec 25 '15 at 19:20
4

C allows for various scalar numbers (integers, floating point) to represent time. It needs to be a "... real types capable of representing times" C11 §7.27.1 3,

The range and precision of times representable in clock_t and time_t are implementation-defined. C11dr §7.27.1 4

The difference between 2 time_t values, as a double affords a vary wide range and precision.

OP, "Since 'number of seconds' doesn't require floating-point numbers, why does this function return a double?


[Edit] Linux/posix might not use fractions of seconds, but other systems have done so. The C standard that defines difftime() choose double and that accommodates an integer accumulation of seconds as well as other OS implementations.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256