[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Feature request: gcc should warn upon conversions ptrdiff_t -> int



Phil Edwards <phil@jaj.com> writes:

> > int foo(int *x, int *y)
> > {
> >      return x - y;
> > }
> 
> There is no conversion to int.  foo* may be subtracted from foo* for any
> type foo.  It's normal pointer arithmetic.  This code is fine.

You are missing the point. The result of the subtraction is of type
ptrdiff_t (which is fine), but then, on the return, that gets
converted to int.

> > This code is correct on 32-bit machines, but it is likely to be wrong
> > on machines with 64-bit pointers and 32-bit integers.  If possible,
> > the warning should be issued on 32-bit machines, too, to help prevent
> > future problems.
> 
> Pointers can be 42.69 bits wide, and the code would still be correct.

No. In that case, ptrdiff_t most likely would be an integral type with
42.69 bits, and conversion to int would cause loss of
precision. Matteo requests that a warning is issued for size kind of
conversion (probably also from size_t to int), as on some systems,
sizeof(ptrdiff_t) > sizeof(int). That would be something like
-W64bit-portability.

Regards,
Martin



Reply to: