mardi 26 juillet 2016

Why does it matter to put the else statement on a new line? [duplicate]

This may be a basic question, but I couldn't find an answer anywhere. I was just told to put the else statement between curly brackets because of 'style' and nothing more.

Consider the following example. Suppose we have 10 students and each got a mark for a test between 1 and 10. A 5.5 or higher is a pass and a fail otherwise.

set.seed(123)
student <- 1:10
marks <- round(runif(10, 1, 10), digits = 1)
df <- data.frame(student, marks)

The first student got a 3.6 so he failed his test. If I do the following:

if (df$marks[1] >= 5.5)
{
  result <- "Pass"
}
else
{
  result <- "Fail"
}

I get the error:

Error: unexpected 'else' in "else"

The following works:

if (df$marks[1] >= 5.5)
{
  result <- "Pass"
}else{
  result <- "Fail"
}

So I thought, if i don't put the else on the same line, the code thinks the if statement has ended and therefore doesn't know what to do with else.

However, I wonder why the following works:

for (i in 1:nrow(df))
{
  if(df$marks[i] >= 5.5)
  {
    df$result[i] <- "Pass"
  }
  else
  {
    df$result[i] <- "Fail"
  }
}

Can anybody tell me why the else statement can't begin on a new line outside a for loop, but it can on the inside? I always do }else{ as I am sure this always works, but I hope somebody can satisfy my curiosity.

Aucun commentaire:

Enregistrer un commentaire