CppCoreGuidelines
CppCoreGuidelines copied to clipboard
ES.75 - Exception when defining function-like macros?
Hi,
ES.75 flags the usage of do-while statements. Would you be open to adding an exception when defining function-like macros? It's fairly standard "best practice" to avoid macro pitfalls:
#define MY_MACRO(x) \
do { \
foo(x); \
bar(x); \
} while (0)
The enforcement could be updated to something like "flag do-statements, except if the condition in the while statement is a literal 0 or false".
Thanks!
The guideline has said "Yes, there are genuine examples where a do-statement is a clear statement of a solution, but also many bugs."
As a non-native English speaker, I find that the above sentence is slightly contradictory given that two opposite statements are placed in the same sentence. I read it as:
"...a do-statement is a clear statement of a solution, but also a source of many bugs".
In that case I'd suggest removing the "but also many bugs" part or moving it to the Reason section above. IMHO it fits better there because it's part of the rationale ("avoid do because it causes many bugs"). The Note would then remain as:
"Yes, there are genuine examples where a do-statement is a clear statement of a solution."
For even more clarity, perhaps an example of a "genuine example" could be added to the above statement?
"...a do-statement is a clear statement of a solution, but also a source of many bugs".
In that case I'd suggest removing the "but also many bugs" part or moving it to the
Reasonsection above. IMHO it fits better there because it's part of the rationale ("avoiddobecause it causes many bugs"). TheNotewould then remain as:"Yes, there are genuine examples where a do-statement is a clear statement of a solution."
For even more clarity, perhaps an example of a "genuine example" could be added to the above statement?
the problem with the but also a source of many bugs portion is that it will be very hard to find a clear case where the do{}while() loop is the source of the bug itself; changing to using for(...){} instead would be just as if not more problematic; similarly with while(){}. Rather the guidelines should favor explicitness in loop types:
- counting/iterative ➡️
for(){} - pre-test ➡️
while() {} - post-test ➡️
do{}while()and honestly with those simple guidelines the code tends to be extremely clear.
Editors call: We think this is covered by ES.31. Thanks!
We think it is as clear as we can make it
Thanks for the feedback!