12.1 and for-loops

6.12 Expressions

Moderators: misra-c, david ward

Locked
gs
Posts: 87
Joined: Thu Nov 18, 2004 1:39 am

12.1 and for-loops

Post by gs » Wed May 14, 2008 7:48 pm

Given the code:

Code: Select all

void f()
    {
    int i, j;
    for( i =0, j = 0; i < 10; i++, j++ ) {}
    }
does rule 12.1 'advise' (instead of 'require') I place '()' around the for-loop initializers? In other words, to what extent does this rule apply in the head of a for-loop? The precedence relied on is the precedence of the '=' operator with respect to the ',' operator.
Last edited by gs on Thu May 15, 2008 4:33 pm, edited 1 time in total.

Lundin
Posts: 70
Joined: Mon Dec 10, 2007 1:57 pm

Re: 12.1 and for-loops

Post by Lundin » Thu May 15, 2008 11:25 am

I'm not sure if I understand the question, since I see no case in that example where the code relies on operator precedence.

However, note that rule 12.10 (req) forbids the comma operator.

misra-c
Posts: 566
Joined: Thu Jan 05, 2006 1:11 pm

Re: 12.1 and for-loops

Post by misra-c » Tue May 20, 2008 6:09 pm

Note, use of the comma operator is banned under Rule 12.10.

If no reliance is being placed on C's operator precedence then the loop should be written:

Code: Select all

for ((i = 0), (j = 0); i < 10; i++, j++) {}
Rule 12.1 recognises that it would clutter code considerably if every expression were parenthesised. It leaves the matter of what constitutes "too much" clutter up to individual or organisational choice.
---
Posted by and on behalf of
the MISRA C Working Group

Locked

Return to “6.12 Expressions”