MISRA Discussion Forums

Full Version: 19.4 do while(0)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I would recommend the committee to rephrase rule 19.4 so that it does not allow do-while-zero inside function-like macros.

The do-while-zero mechanism has only two purposes:

/* "goto wrapper" */
} while(0);
The above code is a "hack" to stay compliant with rule 14.4 (goto shall not be used). But it surely leads to even less readable code than goto does.

/* "if-statement fiasco saver" */
#define FUNC(x) do
} while(0)  /* no semicolon here, as enforced by 19.4 */

  FUNC(X); /* the macro allows the semicolon to be placed here */
The above is a "hack" that only applies to code non-compliant to rule 14.9 (if shall be followed by a compound statement). The sole purpose of do-while-zero is to save non-compliant code from the compiler errors it would otherwise receive! If the macro was written as two braces without the do while, there would be a compiler error because of the semicolon.

To sum this up: if code is to conform with (required) rules 14.4 and 14.9, then there is no reason for rule 19.4 to allow do-while-zero.
Again I personally feel that MISRA-C: 1998 had this sorted with Rule 58.
I think good code and design does not need break statements (except in switch statements).

The goto statement has it's uses. Jumping out of nested block statements to error handling code in the case of an error is one such use.
It is better to create a deviation than to create convoluted code simply to comply with the MISRA rules.
The main issue here is example number 2, where rule 19.4 encourages using do-while-zero statements in macros, and thereby effectively disabling compiler errors for violations against rule 14.9.
Example number 1 was just posted to illustrate another obscure and far less frequent usage of do-while-zero.

Btw, the macro should of course have '\' symbols at each line, just as the macro example in rule 19.4.
Hi Lundin,

I agree with you.
This time I think MISRA-C :1998 also had it correct with Rule 90!
Again, I think deviations for the odd case when one cant comply would be preferable to changing the rules to allow bad code to comply.
In my view MISRA-C:1998 is much better than MISRA-C:2004 even if there are a few ambiguities.
My suggestion is to create your own programming standards and use MISRA as a basis. Tighten up the rules in MISRA-C:2004 and don't discount what MISRA-C:1998 had to say!
It is my opinion that MISRA should be used as a minimal set of rules. There are lots more you can add.
The MISRA C Working Group is considering the wording of Rule 19.4 for a future version of MISRA C and will take these comments into consideration.