MISRA Discussion Forums

Full Version: 13.5 clarification on loop index iusage
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear Misra Committee,

Rule 13.5 seems not clearly explicit about the content of the for expressions.
  • First expression: Initialization of the loop coounter if present. Can we consider as valid code the following examples:
    [code]
    int32_t i=0;

    for (i++;i
My opinion is that MISRA 13.5 could be formulated clearer. It says that the first expression of the loop should only initialize the loop counter. But if we are speaking of strict programming terms, initialization refers only to:

int i = 0;

and not to

int i;
i=0;

The first example is initialization, the second one is assignment. The difference is very important if the code for example is ported to C++, where there is a big difference between initialization and assignment. C++ programmers would definitely only consider the first example as initialization, and it is safe to assume that plenty of C++ programmers end up writing C programs.
C++ also allows initialization within the for-loop, as it allows variable declarations there. C does not.

Perhaps the MISRA rule should be formulated as this:
"Fist expression Assigning a value to the loop counter by using the assignment operator (=)."

---

Regarding the second expression in the original post: calling a function from the test part of the loop is usually not smart performance-wise. You will get the function calling overhead each time you run the loop. Though as long as the counter test code is clear, I don't see how it would make the code less safe, which should be MISRA's only concern.
These forms of loop are far from ideal, but do comply with the requirements of Rule 13.5 as written.

Use of for loops in this way will be reviewed and may be deprecated in subsequent versions of MISRA C.

[ID:0000011]