From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 2578 invoked by alias); 22 Sep 2004 13:39:22 -0000 Mailing-List: contact gcc-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Archive: List-Post: List-Help: Sender: gcc-owner@gcc.gnu.org Received: (qmail 2568 invoked from network); 22 Sep 2004 13:39:21 -0000 Received: from unknown (HELO NUTMEG.CAM.ARTIMI.COM) (217.40.111.177) by sourceware.org with SMTP; 22 Sep 2004 13:39:21 -0000 Received: from mace ([192.168.1.25]) by NUTMEG.CAM.ARTIMI.COM with Microsoft SMTPSVC(6.0.3790.0); Wed, 22 Sep 2004 14:39:20 +0100 From: "Dave Korn" To: "'Mathieu Malaterre'" , Subject: RE: Warning flags for unsigned operations (unsafe) Date: Wed, 22 Sep 2004 14:57:00 -0000 MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit In-Reply-To: <4150C8D5.7070200@nycap.rr.com> Message-ID: X-OriginalArrivalTime: 22 Sep 2004 13:39:20.0314 (UTC) FILETIME=[903E5DA0:01C4A0A9] X-SW-Source: 2004-09/txt/msg01276.txt.bz2 > -----Original Message----- > From: gcc-owner On Behalf Of Mathieu Malaterre > Sent: 22 September 2004 01:36 > Hello, > > I have been googling around and I couldn't find out if > gcc had a > warning flag for unsigned operation. For example, even the linear > interpolation on [a,b] can be tricky to code: > > 1. > c = a + t * (b - a); //unsafe > > 2. > c = (1.0 - t) * a + t * b; //safe > > Number 1 will fail when both a and b are unsigned and let say > b - a = -1 > (math speaking). Is there something in gcc that could warn me > for this > kind of operation ? Your code has a design flaw and is not valid. If you want to do maths that involves negative quantities, you HAVE to use a signed variable, not an unsigned one. If you want to do subtraction with unsigned quantities and have it work, you have to ensure (by a test) to always subtract the smaller from the larger. Number 2 only works because you promote all the unsigned variables to floating point quantities, which are always signed, before you subtract them. If you really want to do this crazy thing with signed variables, you HAVE to code it like this: c = (a < b) ? (a + t * (b - a)) : (b + (1.0 - t) * (a - b)); [erm. not quite sure if I transformed the second part of that quite right, but you get the point.] So why not just use signed variables or signed subtraction ? c = a + t * ((int)b - (int)a); [In fact, if I recall the sign-vs-value-preserving rules correctly, it should suffice to cast only one of the arguments to int, shouldn't it?] cheers, DaveK -- Can't think of a witty .sigline today....