Here is the code:
#include <Rcpp.h>
#include <iostream>
#include <assert.h>
#include <stdio.h>
using namespace Rcpp;
// [[Rcpp::export]]
double eudist(NumericVector x, NumericVector y) {
int nx = x.size();
int ny = y.size();
std::cout << nx << '\n' << ny << std::endl;
assert(nx == ny);
double dist=0;
for(int i = 0; i < nx; i++) {
dist += pow(x[i] - y[i], 2);
}
return sqrt(dist);
}
After sourcing it into R, I get the following result, apparently it does not abort when there is an error:
#////////////////////////////////////////////////////
sourceCpp('x.cpp')
#////////////////////////////////////////////////////
eudist(c(0, 0), c(1, 1))
2
2
[1] 1.4142
#////////////////////////////////////////////////////
eudist(c(0, 0), c(1, 1, 1))
2
3
[1] 1.4142
The assert() function tests the condition parameter. If it is false, it prints a message to standard error, using the string parameter to describe the failed condition. It then sets the variable _assert_exit to one and executes the exit statement. The exit statement jumps to the END rule.
If the argument of the MFC ASSERT macro evaluates to zero or false, the macro halts program execution and alerts the user; otherwise, execution continues. When an assertion fails, a message dialog box shows the name of the source file and the line number of the assertion.
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.
The assert Statement If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.
Note that assert()
etc are explicitly prohibited for CRAN uploads. Quoting from the CRAN Repo Policy page:
The code and examples provided in a package should never do anything which might be regarded as malicious or anti-social. The following are illustrative examples from past experience.
- Compiled code should never terminate the R process within which it is running. Thus C/C++ calls to
assert
/abort
/exit
, Fortran calls toSTOP
and so on must be avoided. Nor may R code callq()
.
So the answer about debug mode is technically correct, but also note that you are not supposed to use this if you plan to upload CRAN at some point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With