if {…} else {…} : Does the line break between “}” and “else” really matters?

北战南征 提交于 2020-01-20 08:06:18

问题


I write my if {...} else {...} statement in R in the following way as I find it more readable.

Testifelse = function(number1)
{
     if(number1>1 & number1<=5)
     {
          number1 =1
     }
     else if ((number1>5 & number1 < 10))
     {
          number1 =2
     }
     else
     {
          number1 =3
     }

     return(number1)
}

According to ?Control:

... In particular, you should not have a newline between } and else to avoid a syntax error in entering a if ... else construct at the keyboard or via source ...

the function above will cause syntax error, but actually it works! What's going on here?

Thanks for your help.


回答1:


Original question and answer

If we put in R console:

if (1 > 0) {
  cat("1\n");
  }
else {
  cat("0\n");
  }

why does it not work?

R is an interpreted language, so R code is parsed line by line. (Remark by @JohnColeman: This judgement is too broad. Any modern interpreter does some parsing, and an interpreted language like Python has no problem analogous to R's problem here. It is a design decision that the makers of R made, but it wasn't a decision that was forced on them in virtue of the fact that it is interpreted (though doubtless it made the interpreter somewhat easier to write).)

Since

if (1 > 0) {
  cat("1\n");
  }

makes a complete, legal statement, the parser will treat it as a complete code block. Then, the following

else {
  cat("0\n");
  }

will run into error, as it is seen as a new code block, while there is no control statement starting with else.

Therefore, we really should do:

if (1 > 0) {
  cat("1\n");
  } else {
  cat("0\n");
  }

so that the parser will have no difficulty in identifying them as a whole block.

In compiled language like C, there is no such issue. Because at compilation time, the compiler can "see" all lines of your code.


Final update related to what's going on inside a function

There is really no magic here! The key is the use of {} to manually indicate a code block. We all know that in R,

{statement_1; statement_2; ...; statement_n;}

is treated as a single expression, whose value is statement_n.

Now, let's do:

{
  if (1 > 0) {
    cat("1\n");
    }
  else {
    cat("0\n");
    }
}

It works and prints 1.

Here, the outer {} is a hint to the parser that everything inside is a single expression, so parsing and interpreting should not terminate till reaching the final }. This is exactly what happens in a function, as a function body has {}.



来源:https://stackoverflow.com/questions/37929184/if-else-does-the-line-break-between-and-else-really-matters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!