Home > Enterprise >  combine "while" and "for" loop in C, for user to choose to loop forever or loop
combine "while" and "for" loop in C, for user to choose to loop forever or loop

Time:05-01

I would like to combine a for loop and while loop, where user can choose to loop until it passes or loop a number of time and return fail if it doesn't pass:

uint8_t SomeFunc(uint32_t LoopCnt, unit32_t LoopForever)
{

    uint8_t result = FAIL;
    if(LoopForever != FALSE)LoopCnt = -1; /*max out LoopCnt if LoopForever is set*/

    do{
        for(i = 0; i < LoopCnt; i  ){
            result = Func();
            if (result == PASS) break;
        }

    }while(LoopForever & (result == FAIL))/* do while loopforever is set and the result is fail */

    return result;

}

Is there a better way to write this? with better performance and less code size? it's in C. The solution can use no loop to achieve basically anything you can comeup with that do the same logic. Thanks

CodePudding user response:

Do you really 'need' to combine while and for?

uint8_t SomeFunc(uint32_t LoopCnt, uint32_t LoopForever) {
    
    uint8_t result = FAIL;
    
    while (result == FAIL && (LoopForever || LoopCnt--)) {
        result = Func();
    }

    return result;
}

CodePudding user response:

Candidate alternative assuming result can only have values of PASS or FAIL.

When LoopCnt == UINT32_MAX, i <= LoopCnt; is forever true.

Code uses <= test instead of <. We simple need to test the LoopCnt == 0 case and then decrement LoopCnt.

uint8_t SomeFunc(uint32_t LoopCnt, unit32_t LoopForever) {
  uint8_t result = FAIL;
  if (LoopCnt > 0 || LoopForever != FALSE) {
    LoopCnt--;
    if (LoopForever != FALSE) {
      LoopCnt = UINT32_MAX;
    }
    for (uint32t i = 0; i <= LoopCnt; i  ){
      result = Func();
      if (result == PASS) {
        return result;  // Return now.
      }
    }
  }
  return result;
}

The advantage of @Dave Meehan good answer is clarity, yet with 3 tests per iteration. This code has 2 iterations per loop. Only in select cases e.g. 3% of the time are the fewer tests preferable.

  • Related