Documenting Function-Like Macros [DI23] [WHAT] [WHY] [HOW]

Documenting Function-Like Macros [DI23] [WHAT] [WHY] [HOW]

Tip DI23

Languages like C++ allow you to define preprocessor macros that behave like functions. Because such macros can be cryptic and hard to debug when something goes wrong, they are often worth documenting.

Ensure the following are clear:

  1. The purpose of the macro.

  2. How to use the macro. This includes parameters. Examples of how the macro should be used or how it is expanded may help.

See the following for an example:

/// A wrapper that helps support both asserts in debug builds and sufficient /// conditional execution in release builds. An assert statement will be made, /// followed by the start of an `if` block - the user is responsible for /// finishing the `if` block. See examples below. /// /// For debug builds, it is often useful to have asserts for quickly catching errors. /// However, for release builds where asserts are removed, it is often useful to /// still have protections based on altered logic flow based on the condition. /// This macro helps simplify these scenarios by providing the ability to both /// assert and check a condition with effectively a single line, rather than needing /// to manually call `assert()` and then write a separate `if` statement. /// /// The goal is to replace code like this: /// \code{.cpp} /// assert(condition); /// if (condition) /// { /// // Code for if the condition is true... /// } /// \endcode /// /// With code like the following: /// \code{.cpp} /// ASSERT_THEN_IF(condition) /// { /// // Code for if the condition is true... /// } /// \endcode /// This macro is only responsible for the `ASSERT_THEN_IF(condition)` line above - /// the curly braces and any subsequent logic are the responsibility of users. /// /// \param[in] condition - The boolean condition to check. #define ASSERT_THEN_IF(condition) assert((condition)); if ((condition))

 

Code More Meet Less Ad.png