Function call inside assert == bad?

I just dug up an error in some code we are working with *, which did not work due to the following situation:

Assert(SomeVitalFunction(foo) == OK) 

This worked perfectly all the time when the DEBUG macros were #defined:

 #ifdef DEBUG #define Assert(x) if((x) == 0){/*some error handling*/} #else #define Assert(x) #endif 

But when we #undef'd DEBUG , this #undef'd DEBUG call to the vital function from the code.

I can't figure out for my whole life how this can work with DEBUG #undef 'd, and it seems like a bad idea, as a rule, to place a call to some function inside such a statement.

Did I miss something?

* = Edit to clarify the following Carpetsmoker comment: The code comes from an especially backward bondage of Elbonian code slaves, our task was to crack, cut, shave, polish, sanitize and put lipstick on the item.

+5
source share
2 answers

You have not missed anything.

Statements should always be written as if they might disappear when the compiler switch is clicked.

You can call functions that take a relatively long time to complete inside the assert (for example, by analyzing the integrity of the data structure), since the function call will not be present in the release assembly. The flip side of this is that you cannot invoke the functions necessary for proper operation.

+5
source

It depends on what SomeVitalFunction does. If it has no interesting side effects, it is normal to use it inside an assert . But if calling or not calling SomeVitalFunction is important to the program, this is a mistake.

For example, in POSIX kill (2) with signal 0, it is only useful to check if the process is alive. I would suggest that sometimes you might be tempted to use

  assert(kill(sompid, 0) == 0); // process sompid exists 

assuming you always believe the sompid process is still running.

Similarly, you can use assert(hash_table_count(htbl)>0); to verify that some htbl hash table htbl not empty.

BTW, note that assert (3) is documented as ignored if you are compiling with the -DNDEBUG preprocessor -DNDEBUG (not if -DDEBUG not specified).

+2
source

Source: https://habr.com/ru/post/1208235/


All Articles