Path: csiph.com!news.mixmin.net!eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: Increment/decrement a variable with a maximum Date: Sun, 18 Dec 2022 16:41:14 -0800 Organization: A noiseless patient Spider Lines: 24 Message-ID: <86a63k2pjp.fsf@linuxsc.com> References: MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader01.eternal-september.org; posting-host="ff406b04d09b824d6c1109f51ef0323b"; logging-data="98198"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1++orqkvcltudPnZMMbfY51Jw9AQu2bkUU=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:e3FkYu2qrT7jadul/6cX6SPYfyM= sha1:Fpss0yVgrTD7DHlYHGQm0a9B97A= Xref: csiph.com comp.lang.c:168585 pozz writes: > 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. > > > Could you suggest a better method? [...] a = max > a && max - a > b ? a + b : max; > And for decrement? After seeing the expression for increment, exercise for the reader.