rmaicle

Programming is an endless loop; it's either you break or exit.

Licensed under a Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA).
You are free to copy, reproduce, distribute, display, and make adaptations but you must provide proper attribution. Visit https://creativecommons.org/ or send an email to info@creativecommons.org for more information about the License.

Conditional Assertion

Date: 2016-02-19 08:01:55 +0000

The scenario that lead to this idea does not occur much but I thought it would be good to take a note of it. Here is a made-up function that slightly captures the use case.

1
2
3
4
5
6
7
8
9
10
void check(std::vector<int> lines) {
    auto size = lines.size();
    ASSERT(size > 0);
    if (size <= 2) {
        ASSERT(lines[0] == 1);
    } elseif (size > 2) {
        ASSERT(lines[lines.size() - 1] == 1);
    }
    ...
}

Using something like a conditional assert macro would unclutter it a bit.

1
2
3
4
5
6
7
void check(std::vector<int> lines) {
    auto size = lines.size();
    ASSERT(size > 0);
    IF_ASSERT(size <= 2, lines[0] == 1);
    IF_ASSERT(size > 2, lines[size - 1] == 1);
    ...
}

The idea is that if a certain pre-condition is true then the assert condition is evaluated and that if the assert condition evaluates to false then an assertion is triggered.

1
2
3
4
5
6
#define IF_ASSERT(precond, cond, ...)       \
    do {                                    \
        if (!!(precond)) {                  \
            ASSERT(cond, ##__VA_ARGS__);    \
        }                                   \
    } while ((void)0, 0)
  •  assertion
  •  thoughts