Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 4 Jun 2001 02:43:02 +1000 (EST)
From:      Bruce Evans <bde@zeta.org.au>
To:        Erik Trulsson <ertr1013@student.uu.se>
Cc:        arch@FreeBSD.ORG
Subject:   Re: time_t definition is worng
Message-ID:  <Pine.BSF.4.21.0106040233500.50292-100000@besplex.bde.org>
In-Reply-To: <20010602222626.A26556@student.uu.se>

next in thread | previous in thread | raw e-mail | index | archive | help
On Sat, 2 Jun 2001, Erik Trulsson wrote:

> On Sat, Jun 02, 2001 at 12:47:32PM -0700, David O'Brien wrote:
> > On Sat, Jun 02, 2001 at 10:39:09AM -0700, Matt Dillon wrote:
> 
> When using a time_t in printf(3) or similar situations the 'correct'
> thing is to cast the time_t value to a long and treat it is a long.

This is only correct in current versions of POSIX.  In C90, time_t
can be any arithmetic type.  It might be "unsigned long", in which
case casting it to long might change its value.  OTOH, casting it to
"unsigned long" would be wrong if it were "long".  It might be "long
double", in which case casting it to long might cause an overflow
trap.  In any case, the representation of time_t's in implementation-
defined so printing them directly is only portably useful for
debugging.  Things are a little more complicated in C99, since there
may be more arithmetic types.  Things are a little less complicated
in POSIX, since the representation of time_t is defined.

> I.e.
> 
> time_t t;
> ...
> printf("%ld",(long)t);
> 
> Then the code will work regardless of whether time_t is defined as an
> int or as a long. (And regardless of wether sizeof(int) == sizeof(long)
> or not.)

I always use this in practice :-).

> (If time_t is defined as a long long then the above code won't work
> unless sizeof(long) == sizeof(long long). Code like the above that
> assumes that a time_t can fit in a long probably exists in *many*
> programs. Changing time_t to a 'long long' might therefore break quite
> a lot of things.)

In POSIX, the representation is known, so we know that casting to long
gives the correct result on all machines for times between 1970 and
2038.

Bruce


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-arch" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.BSF.4.21.0106040233500.50292-100000>