For Loop: must update expression use only invariants?

Moderators: david ward, misra cpp

swestin
Posts: 8
Joined: Wed May 28, 2014 6:53 pm
Company: GrammaTech Inc.

For Loop: must update expression use only invariants?

Postby swestin » Wed Nov 29, 2017 3:47 pm

MISRA C:2012 Rule 14.2 puts the following restriction on the "third clause" (called "expression" in C++:2008):

Shall not use objects that are modified in the for loop body.

For example, the following violates this rule:

Code: Select all

    for (int i=0; i<500; i = i + j)
    {
        j = random();
    }


I can't find a corresponding rule in C++:2008. Am I overlooking something?

- Stephen H. Westin

misra cpp
Posts: 145
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: For Loop: must update expression use only invariants?

Postby misra cpp » Wed Jan 17, 2018 4:37 pm

Your example violates rule 6-5-4

i is a loop counter (initialised before the condition, tested with a relational operator in the condition and modified in the expression).

6-5-4 requires that the loop counter shall only be modified by one of ++ -- += n or -= n where n is constant for the duration of the loop
Posted by and on behalf of
the MISRA C++ Working Group


Return to “6.6 Statements (C++)”

Who is online

Users browsing this forum: No registered users and 2 guests