🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4580

Re: Undefined result vs. int's holding undefined values.

#4580
From: Thad Smith
Date: Sun, 07 Jan 1996 22:41
28 lines
1473 bytes
In article <4cmg0s$1mb@der.twinsun.com>,
eggert@twinsun.com (Paul Eggert) wrote:
>This reminds me of a similar bug I found a long time ago when porting
>the Modula-3 runtime, which contained code that acted something like this:
>
>	int sum_overflow (int x, int y) {
>		return (x + y < x) != (y < 0);
>	}
>
>The C Standard does not guarantee that the above function works,
>since integer overflow leads to undefined behavior,
>but when I found that the function did not work with whatever old version
>of GCC I was using at the time, I reported it as a bug to the GCC maintainers
>and got a fix from them in a few days.
>
>Regardless of what the C Standard says, it should be obvious that it's
>crucial to have integer overflow checking working properly in an
>application that needs it.  

I agree, but it is possible to rewrite the function so that it doesn't
invoke undefined behavior:

  #include <limits.h>
  int sum_overflow (int x, int y) {
      return x > 0? (y > INT_MAX - x) : (y < INT_MIN - x);
  }

Thad
Technical Details
Message-ID: <oZA8wQ9ytpjN084yn@csn.net>
Path: arc1-ca.pugleaf.net!teal.csn.net!not-for-mail
References: <4ck70b$rd7@news.informix.com> <4ckms5$rd7@news.informix.com> <4cmg0s$1mb@der.twinsun.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!teal.csn.net!not-for-mail
From: thads@csn.net (Thad Smith)
Newsgroups: comp.std.c
Subject: Re: Undefined result vs. int's holding undefined values.
Date: 7 Jan 1996 15:41:47 -0700
Organization: T3 Systems
Message-ID: <oZA8wQ9ytpjN084yn@csn.net>
References: <4ck70b$rd7@news.informix.com> <4ckms5$rd7@news.informix.com>
 <4cmg0s$1mb@der.twinsun.com>
Reply-To: ThadSmith@acm.org
NNTP-Posting-Host: 199.117.27.22