Reputation:
I know that time_t is a long int on my system implementation. For the sake of experimenting, let's initialize it with INT_MAX. The data are displayed correctly, and running the code some second later decreases the counter accordingly.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<limits.h>
int main(){
/* Set the current and a very large time */
time_t now;
time(&now);
time_t max = INT_MAX;
/* Print them on screen. */
printf("Last time: %s", ctime(&max));
printf("\nCurrent time: %s", ctime(&now));
/* Compute their difference */
double remaining = difftime(max, now);
printf("Remaining seconds (difftime): %lf\n", remaining);
return 0;
}
The problem is: when I replace INT_MAX with LONG_MAX, I obtain two apparently strange behaviors.
ctime(&max) returns a NULL. The reason might be that, if I remember correctly, the string is supposed to have maximum length 26, in this case exceeded. Am I right?
if I run the code some seconds later, the variable "remaining" is still the same, conversely to the MAX_INT case where it decreases second after second. How can I explain such a behavior? (these values are surely below DBL_MAX)
EDIT: sorry, I wrote "size_t" instead of "time_t" in my previous version, my mistake.
Upvotes: 2
Views: 232
Reputation: 51835
if I run the code some seconds later, the variable "remaining" is still the same
Assuming your platform uses the IEEE 754 representation for a double
type, then that will have a precision of approximately 16 (decimal) digits. Your (long) long int
type's LONG_MAX
(if 64-bits) has a value (probably) of 9223372036854775807
, which is 19 digits - so you are losing precision when subtracting now
from max
, and the displayed result will appear the same. If you were to wait more than 1,000 seconds between runs, then you would most likely see a difference.
ctime(&max) returns a NULL
See: ctime returning null.
Upvotes: 1
Reputation: 7287
Type time_t
is intended for timestamps.
I don't see why you would want to put LONG_MAX
in there. Chances are its value is too big to properly represent a time stamp the system can handle.
So it would make sense ctime()
doesn't know how to handle it and returns NULL to indicate the error.
About the question why remaining
has the same value when reunning again later, I don't really know, unless ctime(&max)
somehow alters the value of max
.
Upvotes: 0