I've recently faced the same problem and I guess I found a solution. It relies on clang's __builtin_assume
attribute, which will warn if passed expression has side effects. GCC does not have it, so solution is not portable.
The resulting macro is
#define assert(e) do { if (!(e)) { __builtin_assume(!(e)); __assert_fn(); } } while (0);
It should not cause any code-generation issues, since assume is placed on dead branch that should kill a program (if __assert_fn
is declared with noreturn
, then compiler may assume e
anyway).
See gist for example and godbolt link https://gist.github.com/pskrgag/39c8640c0b383ed1f1c0dd6c8f5a832e