Hacker News new | ask | show | jobs
by haberman 2437 days 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)

3 comments

Note 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.
Actually, the argument of MY_ASSERT should always be convertible to bool, even in release mode.
Why 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.
> #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).

You could do sizeof((expr)?1:2) instead, which would also force expr to be contextually convertible to a bool.
sizeof((expr)) would suffice to filter out types.