FW: [casting; overflow detection]

Paul Eggert eggert at cs.ucla.edu
Sat Jan 15 08:02:34 UTC 2011

On 01/14/2011 08:43 PM, Robert Elz wrote:

> If you're going to make that change, which is OK, as date.c doesn't
> need more than that, then you should probably also rename the function

Yes, that'd be fine.

> Most of it is also not needed, the struct tm's are normalised, which means
> that "atmp->tm_hour - btmp->tm_hour" cannot possibly underflow or overflow,

Yes, when they're normalized, only the tm_year subtraction can overflow.
I thought it a bit clearer to use "!=" everywhere if I was to use it
with tm_year, but it's a minor detail.

>   |  	number0 = *number;
>   | +	if (delta < 0 ? number0 < delta - INT_MIN : INT_MAX - delta < number0)
>   | +		  return 1;
> Surely the first test there should be
> 		number0 < INT_MIN - delta
> ?

Yes, that's correct.  Thanks for catching the typo, both there,
and in the "delta - LONG_MIN" case.

> The chances that C will ever
> be used in any meaningful way on any hardware where interger overflow
> doesn't wrap is close to 0

Well, I'm afraid that's not true these days.  With the latest GCC on x86,
the following program exits with status 0 if you compile with "gcc -O2":

  #include <limits.h>
  int x = INT_MAX;
  enum { delta = 1 };
  int main (void) { return (x + delta < x) != (delta < 0); }

even though it should exit with status 1 if integer overflow wraps
around.  "gcc -O2"-on-x86 is a pretty common platform.

More information about the tz mailing list