On 16/08/2019 12:36 p.m., Hugh Parsonage wrote:
I was initially pretty shocked by the result in this question:
https://stackoverflow.com/questions/57527434/when-do-i-need-parentheses-around-an-if-statement-to-control-the-sequence-of-a-f

Briefly, the following returns 0, not 3 as might be expected:

if (TRUE) {
     0
} else {
     2
} + 3

At first I thought it the question was simply one of syntax
precedence, but I believe the result is too surprising to not warrant
note in the documentation of Control. I believe the documentation
should highlight that the `alt.expr` is demarcated by a semicolon or
newline and the end of a *statement*, not a closing brace per se.

Perhaps in the paragraph starting 'Note that it is a common mistake to
forget to put braces...' it should end with. "Note too that it is the
end of a *statement*, not a closing brace per se, that determines
where `alt.expr` ends. Thus if (cond) {0} else {2} + 2 means if (cond)
{0} else {2 + 2} not {if (cond) {0} else {2}} + 2."



I agree this is surprising, and should perhaps be pointed out in the docs, but I don't think your suggestion is quite right. { 2 } + 3 is a legal expression. It doesn't have to be the end of a statement that limits the alt.expr, e.g. this could be one big statement:


 { if (TRUE) {
      0
    } else {
      2
    } + 3 }

What ends alt.expr is a token that isn't collected as part of alt.expr, not just a semicolon (which separates statements) or a newline. I don't know how many of those there are, but the list would include at least
semicolon, newline, }, ), ], and maybe others.

Duncan Murdoch

______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel

Reply via email to