MISRA Discussion Forums
Rule 19.4 do-while(0) for single statements - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4)
+--- Forum: MISRA-C: 2004 rules (https://forum.misra.org.uk/forumdisplay.php?fid=17)
+---- Forum: 6.19 Preprocessing Directives (https://forum.misra.org.uk/forumdisplay.php?fid=43)
+---- Thread: Rule 19.4 do-while(0) for single statements (/showthread.php?tid=963)



Rule 19.4 do-while(0) for single statements - wwinzer - 28-05-2013

While I fully understand the need to weld multiple statements in a function-like macro into a compound statement using the do-while(0) construct, I wonder why rule 19.4 explicitely includes macros with only one statement.
Quote: The do-while-zero construct is used to wrap a series of one or more statements and ensure correct behaviour.

I've searched the net high and low and could not find any reason for requiring single statements to be encapsulated in do-while(0). Could you give an example here of code that breaks when disregarding this rule?


Re: Rule 19.4 do-while(0) for single statements - ChipWeller - 03-06-2013

I believe what they are trying to do is to force your macro statement to require a ";" at the end, making it look like the termination of a C expression-statement. There are only a couple of statements (see C90 section 6.6) that require termination with a ";", the expression-statement, the do iteration-statement and the jump-statement. Since without the ";" the expression-statement is simply an expression, which is allowed by Rule 19.4, I think this makes good sense.

Note that I cannot find this rule in the MISRA C:2012 version, so it may be that the MISRA committee now agrees with your view.


Re: Rule 19.4 do-while(0) for single statements - misra-c - 11-09-2013

The 2004 rule was trying to ensure encapsulation of macros, to prevent unintended consequences.

For 2012 we have tightened the focus of the guidelines to address definite problems, rather than be generic. This was one Rule that has become more focussed.