Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
Alexandru Avatar asked May 03 '11 09:05

Alexandru


People also ask

How do you pass a message in assert?

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.

What does assert () do in C++?

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.

How do you assert a statement in Python?

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.

How do you print assert values in Python?

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!"


2 Answers

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"); 
like image 193
pmg Avatar answered Sep 22 '22 10:09

pmg


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 case x evaluates to false! (First time, when the for loop is checking its condition; second time, when the assert is evaluating the passed expression!)

like image 25
bugfeeder Avatar answered Sep 22 '22 10:09

bugfeeder