Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #163016

Re: How to add ssize_t a by size_t b?

From Tim Rentsch <tr.17687@z991.linuxsc.com>
Newsgroups comp.lang.c
Subject Re: How to add ssize_t a by size_t b?
Date 2021-10-06 04:06 -0700
Organization A noiseless patient Spider
Message-ID <86mtnmquno.fsf@linuxsc.com> (permalink)
References <c64a2f9b-4745-42f4-9bd4-ce093fbc2d68n@googlegroups.com>

Show all headers | View raw


wij <wyniijj@gmail.com> 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
}

Back to comp.lang.c | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

How to add ssize_t a by size_t b? wij <wyniijj@gmail.com> - 2021-10-01 08:32 -0700
  Re: How to add ssize_t a by size_t b? Guillaume <message@bottle.org> - 2021-10-01 19:39 +0200
    Re: How to add ssize_t a by size_t b? scott@slp53.sl.home (Scott Lurndal) - 2021-10-01 18:31 +0000
      Re: How to add ssize_t a by size_t b? Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2021-10-01 14:29 -0700
        Re: How to add ssize_t a by size_t b? James Kuyper <jameskuyper@alumni.caltech.edu> - 2021-10-01 20:17 -0400
          Re: How to add ssize_t a by size_t b? Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2021-10-01 18:42 -0700
            Re: How to add ssize_t a by size_t b? Manfred <noname@add.invalid> - 2021-10-02 20:17 +0200
              Re: How to add ssize_t a by size_t b? James Kuyper <jameskuyper@alumni.caltech.edu> - 2021-10-02 15:03 -0400
    Re: How to add ssize_t a by size_t b? James Kuyper <jameskuyper@alumni.caltech.edu> - 2021-10-01 14:53 -0400
      Re: How to add ssize_t a by size_t b? Tim Rentsch <tr.17687@z991.linuxsc.com> - 2021-10-02 15:13 -0700
  Re: How to add ssize_t a by size_t b? Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2021-10-01 14:13 -0700
    Re: How to add ssize_t a by size_t b? Tim Rentsch <tr.17687@z991.linuxsc.com> - 2021-10-02 14:52 -0700
  Re: How to add ssize_t a by size_t b? Tim Rentsch <tr.17687@z991.linuxsc.com> - 2021-10-02 14:47 -0700
  Re: How to add ssize_t a by size_t b? Tim Rentsch <tr.17687@z991.linuxsc.com> - 2021-10-06 04:06 -0700

csiph-web