This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Suggested warning: "negating an expression of unsigned type does not yield a negative value"
- From: Joe Buck <jbuck at synopsys dot com>
- To: Falk Hueffner <falk dot hueffner at student dot uni-tuebingen dot de>
- Cc: gcc at gcc dot gnu dot org
- Date: Mon, 6 Oct 2003 08:59:58 -0700
- Subject: Re: Suggested warning: "negating an expression of unsigned type does not yield a negative value"
- References: <87zngev8i4.fsf@student.uni-tuebingen.de>
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.