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


Groups > comp.lang.c > #168592

Re: Increment/decrement a variable with a maximum

From antispam@math.uni.wroc.pl
Newsgroups comp.lang.c
Subject Re: Increment/decrement a variable with a maximum
Date 2022-12-19 14:39 +0000
Organization Aioe.org NNTP Server
Message-ID <tnpt3k$4ul$1@gioia.aioe.org> (permalink)
References <tno602$2cj2$1@dont-email.me>

Show all headers | View raw


pozz <pozzugno@gmail.com> wrote:
> Suppose you have two uint32_t variables (a and b) that you want to add 
> together and another uint32_t variable (max) that is the maximum that 
> the result could assume. A silly code could be:
> 
>   a += b;
>   if (a > max) {
>     a = max;
>   }
> 
> Of course, this doesn't work well for every values of a, b and max.
> 
> For example, for a=0xFFFF'FFFC, b=10 and max=0xFFFF'FFFE.


   {
        int64_t tmp = (int64_t)a + (int64_t)b;
        a = (tmp > max)?max:tmp;
   }

Tell compiler what you want and let it do its job at optimization.


> Could you suggest a better method? I'm thinking of:
> 
>     a += b;
>     if ((a < b) || (a > max)) {
>         a = max;
>     }
> 
> And for decrement?

The above generalize in obvious way.

-- 
                              Waldek Hebisch

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


Thread

Increment/decrement a variable with a maximum pozz <pozzugno@gmail.com> - 2022-12-18 23:59 +0100
  Re: Increment/decrement a variable with a maximum Siri Cruise <chine.bleu@yahoo.com> - 2022-12-18 15:07 -0800
  Re: Increment/decrement a variable with a maximum Richard Damon <Richard@Damon-Family.org> - 2022-12-18 19:25 -0500
  Re: Increment/decrement a variable with a maximum Tim Rentsch <tr.17687@z991.linuxsc.com> - 2022-12-18 16:41 -0800
  Re: Increment/decrement a variable with a maximum antispam@math.uni.wroc.pl - 2022-12-19 14:39 +0000
  Re: Increment/decrement a variable with a maximum Kaz Kylheku <864-117-4973@kylheku.com> - 2022-12-20 13:44 +0000
    Re: Increment/decrement a variable with a maximum Kaz Kylheku <864-117-4973@kylheku.com> - 2022-12-20 13:54 +0000
    Re: Increment/decrement a variable with a maximum Jame O' Brian <invalid@gmail.com> - 2022-12-20 18:12 +0000
      Re: Increment/decrement a variable with a maximum Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2022-12-20 18:21 +0000
      Re: Increment/decrement a variable with a maximum "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> - 2022-12-20 12:52 -0800
        Re: Increment/decrement a variable with a maximum Öö Tiib <ootiib@hot.ee> - 2022-12-23 05:21 -0800
          Re: Increment/decrement a variable with a maximum "Chris M. Thomasson" <chris.m.thomasson.1@gmail.com> - 2022-12-23 13:53 -0800

csiph-web