BetterCallMe
BetterCallMe

Reputation: 768

Non-execution of statement in function calling

While working on some problem i came across a situation in which i wanted to know if a function was executed when called upon. To do so i put a print statement in the function.

abc = function(x)
    if(x > 0) {
      return(x)
      print("Go")
    } else {
      return(0)
      print("Run")
    }

y = abc(3)
y
# [1] 3

Why print statement is not executed while calling abc()?

Upvotes: 1

Views: 84

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389155

That is because you are returning before printing. Change the sequence of those two statements and it should print

abc = function(x) {
    if(x > 0) {
      print("Go")
      return(x)
    } else {
      print("Run")
      return(0)
   }
}

abc(3)
#[1] "Go"
#[1] 3

abc(-3)
#[1] "Run"
#[1] 0

Upvotes: 1

Related Questions