3 ms·
One way to solve the do/while(0) problem is by using a “statement expression”. It's a GCC extension, and I don't know the reason it has never been accepted into
by DerekL 9y ago
One way to solve the do/while(0) problem is by using a “statement expression”. It's a GCC extension, and I don't know the reason it has never been accepted into the standard. Here's how it works:
#define my_assert(X) ({ if (!(X)) error(); })
Another way is to use a lambda expression, and then call it immediately:
#define my_assert(X) ( [=]() { if (!(X)) error(); } )()
Because the lambda captures by copy, it will catch inadvertent side effects in some cases.
You can also use the conditional operator in this case:
#define my_assert(X) ( (X) ? error() : ((void)0) )
- DerekL 9y agoThe last one is backwards, should be: #define my_assert(X) ( !(X) ? error() : ((void)0) )