简体   繁体   中英

Comparing to a counter which reset

I have an uint32 counter. I read this counter and store it like startCount = counter; Then I do some operations and then check again the counter. If counter is greater than startCount+1 (means counter must be incremented at least twice).

if (counter > startCount +1 )
  break;

Now the counter will be reseted to zero once it reaches max value for unit32. To compensate this I have added

if (startCount == Max)
  if (counter > 0)
    break;
else
  if (counter > startCount +1) || (counter < startCount)
    break;

My question is: is there a better / smarter way to do that? Thanks for all the help.

Just checking this below should cover everything

if (counter > startCount +1) || ( (counter != startCount) && (counter < startCount +1)) 
    break;

`

I'd use

if (counter-startCount > 1) break;

or, if I'd want to allow for int having more than 32 bits,

if ((uint32_t)(counter-startCount) > 1) break;

the number of increments computes modulo 2 32 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM