Skip to content
Prev 26658 / 63424 Next

C/C++ 'assert' should not be used in R packages

On 10/11/2007 4:27 PM, Simon Urbanek wrote:
Perhaps I use assert() differently than you, but the way I use it is to 
assert assumptions that I believe will always be true.

If one of those assertions fails, it means that my program is operating 
in a way that I did not foresee.  I can't recover gracefully from that, 
because at that point my basic assumptions about the program have been 
proven to be incorrect.  I have no basis for reasoning.  It is by 
definition a bug.

Now, it's possible that this bug has corrupted R and it really would be 
best for the user to discard all his work, but I agree that's unlikely. 
  That's why I proposed that R should offer a way to handle an assertion 
failure that limits the shutdown to just my package.

I don't offer a guarantee that my work won't corrupt a user's data, but 
I do work hard to avoid that.  Allowing my package to tell the user that 
it is now unsafe to use is one way to do so.  That's what assert() is for.

In a standalone program, an (uncaught) assertion failure will cause the 
RTL to shut down the process.  I think R should support a version of 
that, but limit the shutdown to the package that has failed.   The 
version of assert() that I put together for rgl this morning doesn't 
attempt to shut down rgl, because that's really something that R should 
be responsible for.  All it does is issue a dire warning to the user.

Offline, Brian mentioned that some packages use assert() for input 
validation.  That's an incorrect use of it, and those packages should 
use error(), as Brian suggested.

Duncan Murdoch