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?
A hack I've seen around is to use the && operator. Since a pointer "is true" if it's non-null, you can do the following without altering the condition: assert(a == b && "A is not equal to B"); Since assert shows the condition that failed, it will display your message too.
Answer: An assert in C++ is a predefined macro using which we can test certain assumptions that are set in the program. When the conditional expression in an assert statement is set to true, the program continues normally. But when the expression is false, an error message is issued and the program is terminated.
The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.
Assertions can include an optional message, and you can disable them when running the interpreter. To print a message if the assertion fails: assert False, "Oh no! This assertion failed!"
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");
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With