4 ms·
This seems like a potential solution to the problem of how to #define MY_ASSERT(x) in release mode such that it fails to compile if "x" is not a valid expressio
by haberman 7y ago
This seems like a potential solution to the problem of how to #define MY_ASSERT(x) in release mode such that it fails to compile if "x" is not a valid expression.
Previous I have used this idiom:
#define MY_ASSERT(expr) do {} while (false && (expr))
Another possible alternative might be:
#define MY_ASSERT(expr) sizeof(expr)
- jcranmer 7y ago> #define MY_ASSERT(expr) sizeof(expr) sizeof accepts a type or an expression as its input, so it would compile successfully if expr were a type but not a valid expression (say, int).
- edflsafoiewq 7y agoYou could do sizeof((expr)?1:2) instead, which would also force expr to be contextually convertible to a bool.
- pandaman 7y agosizeof((expr)) would suffice to filter out types.
- leni536 7y agoNote that lambda expressions are not allowed in an unevaluated context. What about this? #define MY_ASSERT(expr) do {} while (false && ((expr), false)) This doesn't require expr to be convertible to bool.
- DerekL 7y agoActually, the argument of MY_ASSERT should always be convertible to bool, even in release mode.
- DerekL 7y agoWhy not just #define MY_ASSERT(expr) ((void)(false && (expr))) The problem the do-while idiom is that the macro result is not an expression, so it can’t be used in certain cases.