Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function call inside assert == bad?

I have just dug up a bug in some code we're working with* that was failing due to the following situation:

Assert(SomeVitalFunction(foo) == OK)

This worked fine all the time 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 it has the effect of deleting the vital function call from the code.

I can't for the life of me work out how that could ever work with DEBUG #undef'd, and it seems a bad idea generally to put any sort of function call inside an assert like this.

Have I missed something?

* = Edit to clarify following Carpetsmoker's comment: The code comes from a particularly backward cabal of Elbonian code slaves, our task has been to hack, slash, shave, polish, sanitize and apply lipstick to the thing.

like image 702
John U Avatar asked Dec 03 '14 13:12

John U


1 Answers

You have missed nothing.

Asserts should always be written as if they could disappear at the flick of a compiler switch.

You can call functions that take a relatively long time to complete inside an assert (for example analysing the integrity of a data structure), because the function call will not be present in the release build. The flip side of this is that you cannot call functions that are necessary for correct operation.

like image 160
Magnus Hoff Avatar answered Sep 19 '22 08:09

Magnus Hoff