Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`assert` in loop

for(unsigned int i = 0; i < x.size(); i++)
    assert(x[i] > 0);

When not debugging (NDEBUG flag), the resultant is an empty for loop. Is there a clean way to handle this (not executing the empty for loop); preferably without preprocessor directive, since it would defeat the purpose of assert in the first place.

like image 974
aiao Avatar asked Jan 30 '13 16:01

aiao


2 Answers

inline bool all_positive(std::vector<int> const &x)
{
    for (size_t i = 0; i < x.size(); i++)
        if (x[i] <= 0)
            return false;
    return true;
}

then

assert(all_positive(x));

(although this may get you an "unused function" warning when NDEBUG is defined).

like image 120
Fred Foo Avatar answered Oct 06 '22 00:10

Fred Foo


A good optimizer should be able to eliminate the entire loop when NDEBUG is defined (I've just tested mine, and it does do that).

Alternatively, you could surround the entire loop with #ifndef NDEBUG / #endif. You say this "would defeat the purpose of assert in the first place", but I don't really follow the reasoning.

like image 22
NPE Avatar answered Oct 06 '22 01:10

NPE