Original question and answer
If we put in R console:
if (1 > 0) {
cat("1
");
}
else {
cat("0
");
}
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
");
}
makes a complete, legal statement, the parser will treat it as a complete code block. Then, the following
else {
cat("0
");
}
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
");
} else {
cat("0
");
}
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
");
}
else {
cat("0
");
}
}
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 {}
.