Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 0.1.1 Example f4
#1
Hi,

In MISRA C++:2023 TC1 Rule 0.1.1, the comment about example f4() says:

As j is only incremented, no value is overwritten without first being read. Additionally, all iterations
of the loop other than the first observe j after it has been incremented, meaning the write in the
increment is necessary.

This is not technically correct: the *last* iteration of the loop will *not* observe the value of j after it has been incremented. Do you consider that the last increment of "j" violates Rule 0.1.1?

What about this?

Code:
template <int n>
void f()
{
  int j = 0;
  for (int i = 0; i < n; ++i)
  {
    use(j);
    j++;  // Violates Rule 0.1.1 for n == 1?
  }
}

The above code never uses the incremented value of "j" for a template instantiation with "n = 1". Is that a violation of Rule 0.1.1?

I see now that this exact use case was explicitly allowed in the original MISRA C++:2023 document, but removed in the TC1.

Code:
Within a loop, a value may be written to an object with the intent that it will be observed during the
next iteration, meaning that the value written on the last iteration may never be observed. Whilst it is
possible to restructure the loop to avoid this behaviour, there is a risk that the resulting code may be
of lower quality (less clear, for example). This rule therefore considers observation during any iteration
to apply to all values written to such an object, including a value written during the last iteration of a
loop that is not actually observed — see example f3, below.
Reply
#2
Technically you are right, instantiating the template with n == 1 does lead to a violation for j++. However, we'd say that this code is within the spirit of the rule and it's likely to be too complex and confusing to add exceptions to the rule (and potentially many more) to address specific edge cases.

If this causes a problem with an unexpected violation from a tool, then a deviation is an acceptable work-around (and better that a specialisation for n==1)
Posted by and on behalf of
the MISRA C++ Working Group
Reply
#3
We didn't answer your first question: "Do you consider that the last increment of "j" violates Rule 0.1.1?"

The last increment to 'j' does not violate the rule. (Except when n==0) the statement performing the write has one other occurance in the loop which is read, and then observed before being overwritten.
Posted by and on behalf of
the MISRA C++ Working Group
Reply
#4
Thank you for the quick clarification!
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)