assert() with message
I saw somewhere assert used with a message in the following way:
assert(("message", condition));
This seems to work great, except that gcc throws the following warning:
warning: left-hand operand of comma expression has no effect
How can I stop the warning?
Solution 1:
Use -Wno-unused-value
to stop the warning; (the option -Wall
includes -Wunused-value
).
I think even better is to use another method, like
assert(condition && "message");
Solution 2:
Try:
#define assert__(x) for ( ; !(x) ; assert(x) )
use as such:
assert__(x) {
printf("assertion will fail\n");
}
Will execute the block only when assert fails.
IMPORTANT NOTE: This method will evaluate expression
x
twice, in casex
evaluates tofalse
! (First time, when thefor
loop is checking its condition; second time, when theassert
is evaluating the passed expression!)