This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Suggested warning: "negating an expression of unsigned type does not yield a negative value"


On Mon, Oct 06, 2003 at 02:46:43PM +0200, Falk Hueffner wrote:
> I just found yet another bug of the kind:
> 
> int f (int *p, unsigned x) { return p[-x]; }
> 
> which only manifests on 64 bit platforms, because most (all?)
> platforms have wrapping address arithmetic.

The C and C++ standards require that unsigned values obey modulo 2**N
arithmetic, so the value of -x is rigorously defined.
 
> So I was wondering about a general warning about negating unsigned
> values, since I couldn't really think of a legitimate application. 

There are legitimate applications, and I've used them in my code.

> quick check with the gcc source turned up:
> 
> gengtype-lex.l:
>   char *namestart;
>   size_t namelen;
>   [...]
>   for (namelen = 1; !ISSPACE (namestart[-namelen]); namelen++)
> 
> This looks actually invalid to me, although it will probably work
> everywhere.

It's valid everywhere.
 
> In fold_const.c, there's
> 
> case RSHIFT_EXPR:
>       int2l = -int2l;
> 
> also "invalid but works" since it's later passed to a function taking
> int.

Again, this is valid everywhere.
 
> Then there's everybody's favourite idiom "x &= -x", but it can be
> expressed clearer as "x &= ~x + 1".

Again, it's fine as is.  Just the fact that your proposed warning will
turn on at least four complaints against correct usage in gcc shows
that it is not a good idea.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]