Warning flags for unsigned operations (unsafe)

Dave Korn dk@artimi.com
Wed Sep 22 14:57:00 GMT 2004


> -----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....



More information about the Gcc mailing list