Consider this code:
void foo(int n) {
assert(n>=0&&n<=3);
for (int i=0; i<n; i++) {
doSomething();
}
}
Here, there is an assert: n
is between [0;3]. Asserts generally used for checking programmer mistakes. But here, it could be used as a hint to the compiler that n
is between [0;3], so it could optimize better. Maybe it can unroll the loop, and use a jump.
For GCC, we can help the compiler manually:
if (!(n>=0&&n<=3)) __builtin_unreachable();
Here, GCC was actually informed that n is between [0;3], so it could generate better code.
My question is: is it possible to create a (possibly compiler dependent) new_assert
macro, which can tell hints to the compiler in release builds? This solution must be transparent, so it can be a full replacement for the assert
macro. For example, in "new_assert(func());
" func()
must not be called in release builds, if it has side effects.
Or, if it is not possible, another useful new_assert
could be, if the condition is not allowed to have side effects (it would cause compile-time error), so we can use if (!(cond)) __builtin_unreachable();
in release builds without the fear that cond
has a side effect. I.e. is it possible to create a new_assert
that is checked whether its condition has side effects?
This is a related question.
This is a very similar question, but this time I ask whether it is possible to create a full replacement for the assert
macro (so we can avoid manually annotating code)