CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

ES.75 - Exception when defining function-like macros?

Open carlosgalvezp opened this issue 3 years ago • 3 comments

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!

carlosgalvezp avatar Aug 21 '22 15:08 carlosgalvezp

The guideline has said "Yes, there are genuine examples where a do-statement is a clear statement of a solution, but also many bugs."

markyin avatar Aug 23 '22 03:08 markyin

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?

carlosgalvezp avatar Aug 23 '22 05:08 carlosgalvezp

"...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?

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.

BenjamenMeyer avatar Aug 23 '22 14:08 BenjamenMeyer

Editors call: We think this is covered by ES.31. Thanks!

hsutter avatar Sep 22 '22 21:09 hsutter

We think it is as clear as we can make it

BjarneStroustrup avatar Sep 22 '22 21:09 BjarneStroustrup

Thanks for the feedback!

carlosgalvezp avatar Sep 23 '22 07:09 carlosgalvezp