Boost logo

Boost :

Subject: Re: [boost] Current Guidance on Compiler Warnings?
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2018-11-27 03:15:54


On Mon, Nov 26, 2018 at 2:29 PM Steven Watanabe via Boost <
boost_at_[hidden]> wrote:
> AMDG
>
> On 11/26/2018 03:15 PM, Gavin Lambert via Boost wrote:
> > On 27/11/2018 09:40, Emil Dotchevski wrote:
> >> This is not what unsigned is for. You should generally use signed ints
> >> even
> >> if the value can't be negative.
> >
> > Why? Other than being less typing (which is, I think, the real
> > mistake), what reason is there for this?
>
> signed integer overflow has undefined behavior.
> unsigned integers wrap. This means that signed
> integers give the compiler more scope for optimization
> and/or runtime checks.

I thought that signed integer overflow is implementation-defined. But yes,
runtime checks, and not just for the compiler, also in asserts. Given that
signed types implicitly convert to unsigned types, it is precisely when a
number must not be negative that you should use a signed int, so that you
can actually detect bugs when it is negative.

Another reason is that unsigned ints are just wrong sometimes. For example,
if you want to represent width, and you reason that it can't be negative,
and you do:

unsigned width;

On the other hand, coordinates can reasonably be negative, so you use int:

int x;

Then you write something like:

if( x-width<5 )

Oops.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk