Path: csiph.com!news.mixmin.net!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: How to add ssize_t a by size_t b?
Date: Wed, 06 Oct 2021 04:06:51 -0700
Organization: A noiseless patient Spider
Lines: 28
Message-ID: <86mtnmquno.fsf@linuxsc.com>
References:
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="f63a7b6827eb8960d7c84af554cfeab9"; logging-data="28167"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+HF8dxTljm+54zTOkCVnicRdvGx3dpty8="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:1xjIZP+yktRAXlOzfS0ICdO3MOI= sha1:mbNFr9zUS4nhJYdN3YkyCzdnmbs=
Xref: csiph.com comp.lang.c:163016
wij writes:
> To simply the question of "a+b":
>
> ssize_t add(ssize_t a, size_t b) {
> if(a+b would overflow) { set errno=ERANGE; }
> a+=b; // ?
> return a;
> }
>
> Another example:
> ssize_t a=SSIZE_T_MIN;
> size_t b=SIZE_T_MAX;
> a+=b; // Is this OK? Or, How the addition is done correctly?
For those who may be interested, here is a function to compute
the sum when the result is within the range of ssize_t, and
give an error indication when it isn't.
ssize_t
add_ssize_and_size( ssize_t const a, size_t const b ){
if( a >= 0 && SSIZE_MAX - a >= b ) return a + b;
if( a < 0 && b <= SSIZE_MAX ) return a + (ssize_t){ b };
if( a < 0 && b-1-SSIZE_MAX <= -(a+1) ) return b-1 - -(a+1);
return errno = ERANGE, SSIZE_MAX; // or some other suitable value
}