MISRA Discussion Forums

Full Version: Rule 19.4 do-while(0) for single statements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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.
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.