[Rcpp-devel] assert() for Rcpp?

Miratrix, Luke lmiratrix at fas.harvard.edu
Wed Feb 18 01:41:33 CET 2015

Dirk Eddelbuettel and I were discussing how people do not seem to be
putting assert() statements in their C code in Rcpp packages.  I expect
the reason is because assert() prints to cerr, which is a violation of the
CRAN policies of proper packages.  However, the assert() command is a
simple macro, and we could tweak it so it is compliant with CRAN
standards.  Below, I have an example of what might be included.  Dirk
suggested that this idea be posted to this list to gather peoples insights
and thoughts (and to catch any memory management issues, for example, that
might exist with the code below).

The traditional assert() is a macro that calls a function __assert() which
in turn seems fairly simple, but the C program for Rcpp should not just
abort but instead throw an error, I think.  (The macro allows for
detection of line numbers in the code, and also allows for a NDEBUG flag
to omit all asserts for efficient code.)

The proposed code:

#include <stdio.h>

#ifdef NDEBUG
# define assert(EX)
# define assert(EX) (void)((EX) || (__assert (#EX, __FILE__, __LINE__),0))

void __assert (const char *msg, const char *file, int line) {
    char buffer [100];
    snprintf( buffer, 100, "Assert Failure: %s at %s line #%d", msg, file,
line );
    ::Rf_error( buffer );

Anyway, I would love to hear people¹s thoughts on this.  I found assert()
useful in wrapping an existing spaghetti code base with an R package; it
seems like a nice tool to provide enhanced ability to track down bugs.  I
am currently using the above in my package Œtextreg¹ and it appears to
work great.


Luke Miratrix
Assistant Professor of Statistics

	Note: Due to my RSI (wrist trouble), e-mail often abrupt.


Department of Statistics
Science Center

Harvard University
1 Oxford Street
Cambridge MA 02138-2901

lmiratrix at stat.harvard.edu

More information about the Rcpp-devel mailing list