Search code examples
carmstm32microcontroller

Is there any advantage to using for loop with no conditions (for (;;)) instead of a while(true) in embedded C code?


I recently took over an ARM Cortex M4 C code base from another engineer who unexpectedly quit the job. As I was looking through the codes to understand what was going on, I came across several uses of for(;;) structure. I understood it to mean an infinite loop, but is it advantageous to use this over while(1) or while(True)? It's just strange to me why you would want to use an infinite for-loop structure when you don't want to have a starting and stopping condition.

Not sure whether I should leave it be or convert it to a while(true) structure instead. I don't know what's going on at the lower level when you use for(;;) as the structure since, normally a for loop would keep track of the variable count. In the past, when the counting variable like i is declared as an int16, you could have an index overrun when reaching 32,768 for a signed int 16. Maybe for(;;) is just automatically gets substituted as while(1) anyway, so there's no memory overrun.

The firmware produced from this code had issues with unexpectedly stopping ("hanging up") after running for a long time (>4 months), but that could be from various other problems due to memory overrun somewhere else. The codes don't seem to do memory management too well. I don't see any memory clean-up or freeing up array after infinitely running the loop. Anyway, I don't know whether for(;;) would contribute to this, but maybe it's better to use while(true) instead?

The compiler is IAR Workbench for ARM to compile the C code for STM32L4R9x chip.


Solution

  • is it advantageous to use this over while(1) or while(True)?

    No. Code for clarity*1 and save your time for larger issues like "code had issues with unexpectedly stopping".

    BTW: question has while(True) and while(true). Case is important in C and also exactly how was True/true defined? Sticking with for(;;) avoids that issue.

    I don't know whether for(;;) would contribute to this,

    It does not contribute.


    Tip: Posting code is far more informative that only describing code.


    *1 Best to follow your group's coding standard.