Both R
and C
have lexical scope. So assuming that global scope is empty, in C
the following code would not work :
int aux(int arg) {
if (arg > 0) {
int result = 1;
} else {
int result = 0;
}
return result;
}
While in R
the following code :
aux <- function(arg) {
if (arg > 0) {
result = 1
} else {
result = 0
}
return(result)
}
Works properly. Can someone tell me what is the difference in scoping between R
and C
which makes these two functions behave differently?
In R, the expression after the if
condition is evaluated in the enclosing environment:
if (TRUE) environment()
#<environment: R_GlobalEnv>
(Surprisingly, I couldn't find documentation regarding this.)
You can change that by using local
:
aux <- function(arg) {
if (arg > 0) {
local({result <- 1})
} else {
local({result <- 0})
}
return(result)
}
aux(1)
#Error in aux(1) : object 'result' not found
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