Skip to content
Prev 9557 / 10988 Next

[Rcpp-devel] Unintentional modification of vector in place?

Hi Dirk,

Thanks very much! Apologies for posting about something that has been
covered elsewhere, I did search, but clearly not well enough. (Indeed, I
see, this is almost exactly the same issue:
https://stackoverflow.com/questions/11300048/rcpp-pass-by-reference-vs-by-value
)

On (3), apologies for being unclear, of course casting from int to double
isn't an issue. I meant to say it could be an issue the other way around,
namely, double to int. If you instead pass, for example, c(1.1, 2.2, 3.3,
4.4, 5.5, 6.6) to my example function, it'll silently cast that to an
integer vector c(1, 2, 3, 4, 5, 6) (i.e., truncating). That said, this
isn't really unexpected behaviour, rather exactly what you'd expect if you
did {double x = 1.1; int y = (int) x;} in C. I'll pass on writing my own
compiler, at least for now :)

Finally, just to close the loop on this and to make sure I understand... if
I don't want to modify the original vector, I should do this, yes?

cppFunction('IntegerVector test_int_vec(IntegerVector x) {
  IntegerVector y = clone(x);
  for ( R_xlen_t i = 0; i < x.size(); i++ )
    y[i] = y[i] * 2;
  return y;
}')

Thanks again!

Evan
On Mon, Mar 20, 2017 at 11:44 AM, Dirk Eddelbuettel <edd at debian.org> wrote: